blob: 745dfc393840943cd5a7b3e30c8e1092308d1235 [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 Heimesd32ed6f2008-01-14 18:49:24 +00008#include "structseq.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009
Eric Smith8c663262007-08-25 02:26:07 +000010#include "formatter_unicode.h"
11
Guido van Rossum3f5da241990-12-20 15:06:42 +000012#include <ctype.h>
Christian Heimes93852662007-12-01 12:22:32 +000013#include <float.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000014
Christian Heimesbbe741d2008-03-28 10:53:29 +000015#ifdef HAVE_IEEEFP_H
16#include <ieeefp.h>
17#endif
18
Jack Janseneddc1442003-11-20 01:44:59 +000019#if !defined(__STDC__)
Tim Petersdbd9ba62000-07-09 03:09:57 +000020extern double fmod(double, double);
21extern double pow(double, double);
Guido van Rossum6923e131990-11-02 17:50:43 +000022#endif
23
Christian Heimes969fe572008-01-25 11:23:10 +000024#ifdef _OSF_SOURCE
25/* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */
26extern int finite(double);
27#endif
28
Guido van Rossum93ad0df1997-05-13 21:00:42 +000029/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000030#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000031#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000032#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000033
Guido van Rossum3fce8831999-03-12 19:43:17 +000034struct _floatblock {
35 struct _floatblock *next;
36 PyFloatObject objects[N_FLOATOBJECTS];
37};
38
39typedef struct _floatblock PyFloatBlock;
40
41static PyFloatBlock *block_list = NULL;
42static PyFloatObject *free_list = NULL;
43
Guido van Rossum93ad0df1997-05-13 21:00:42 +000044static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000045fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000046{
47 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000048 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
49 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000050 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000051 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000052 ((PyFloatBlock *)p)->next = block_list;
53 block_list = (PyFloatBlock *)p;
54 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000055 q = p + N_FLOATOBJECTS;
56 while (--q > p)
Christian Heimes90aa7642007-12-19 02:45:37 +000057 Py_TYPE(q) = (struct _typeobject *)(q-1);
58 Py_TYPE(q) = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000059 return p + N_FLOATOBJECTS - 1;
60}
61
Christian Heimes93852662007-12-01 12:22:32 +000062double
63PyFloat_GetMax(void)
64{
65 return DBL_MAX;
66}
67
68double
69PyFloat_GetMin(void)
70{
71 return DBL_MIN;
72}
73
Christian Heimesd32ed6f2008-01-14 18:49:24 +000074static PyTypeObject FloatInfoType;
75
76PyDoc_STRVAR(floatinfo__doc__,
77"sys.floatinfo\n\
78\n\
79A structseq holding information about the float type. It contains low level\n\
80information about the precision and internal representation. Please study\n\
81your system's :file:`float.h` for more information.");
82
83static PyStructSequence_Field floatinfo_fields[] = {
84 {"max", "DBL_MAX -- maximum representable finite float"},
85 {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
86 "is representable"},
87 {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
88 "is representable"},
89 {"min", "DBL_MIN -- Minimum positive normalizer float"},
90 {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
91 "is a normalized float"},
92 {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
93 "a normalized"},
94 {"dig", "DBL_DIG -- digits"},
95 {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
96 {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
97 "representable float"},
98 {"radix", "FLT_RADIX -- radix of exponent"},
99 {"rounds", "FLT_ROUNDS -- addition rounds"},
100 {0}
101};
102
103static PyStructSequence_Desc floatinfo_desc = {
104 "sys.floatinfo", /* name */
105 floatinfo__doc__, /* doc */
106 floatinfo_fields, /* fields */
107 11
108};
109
Christian Heimes93852662007-12-01 12:22:32 +0000110PyObject *
111PyFloat_GetInfo(void)
112{
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000113 PyObject* floatinfo;
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000114 int pos = 0;
Christian Heimes93852662007-12-01 12:22:32 +0000115
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000116 floatinfo = PyStructSequence_New(&FloatInfoType);
117 if (floatinfo == NULL) {
118 return NULL;
119 }
Christian Heimes93852662007-12-01 12:22:32 +0000120
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000121#define SetIntFlag(flag) \
122 PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag))
123#define SetDblFlag(flag) \
124 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimes93852662007-12-01 12:22:32 +0000125
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000126 SetDblFlag(DBL_MAX);
127 SetIntFlag(DBL_MAX_EXP);
128 SetIntFlag(DBL_MAX_10_EXP);
129 SetDblFlag(DBL_MIN);
130 SetIntFlag(DBL_MIN_EXP);
131 SetIntFlag(DBL_MIN_10_EXP);
132 SetIntFlag(DBL_DIG);
133 SetIntFlag(DBL_MANT_DIG);
134 SetDblFlag(DBL_EPSILON);
135 SetIntFlag(FLT_RADIX);
136 SetIntFlag(FLT_ROUNDS);
137#undef SetIntFlag
138#undef SetDblFlag
139
140 if (PyErr_Occurred()) {
141 Py_CLEAR(floatinfo);
142 return NULL;
143 }
Christian Heimesd32ed6f2008-01-14 18:49:24 +0000144 return floatinfo;
Christian Heimes93852662007-12-01 12:22:32 +0000145}
146
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000147PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000148PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149{
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000150 register PyFloatObject *op;
151 if (free_list == NULL) {
152 if ((free_list = fill_free_list()) == NULL)
153 return NULL;
154 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000155 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +0000156 op = free_list;
Christian Heimes90aa7642007-12-19 02:45:37 +0000157 free_list = (PyFloatObject *)Py_TYPE(op);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000158 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000159 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000160 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000161}
162
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000163PyObject *
Georg Brandl428f0642007-03-18 18:35:15 +0000164PyFloat_FromString(PyObject *v)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000165{
Christian Heimes99170a52007-12-19 02:07:34 +0000166 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000167 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000168 char buffer[256]; /* for errors */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000169 char *s_buffer = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000170 Py_ssize_t len;
Guido van Rossum2be161d2007-05-15 20:43:51 +0000171 PyObject *result = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000172
Neal Norwitz6ea45d32007-08-26 04:19:43 +0000173 if (PyUnicode_Check(v)) {
Guido van Rossum2be161d2007-05-15 20:43:51 +0000174 s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
175 if (s_buffer == NULL)
176 return PyErr_NoMemory();
Tim Petersef14d732000-09-23 03:39:17 +0000177 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000178 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000179 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000180 NULL))
Neal Norwitz447e7c32007-08-12 07:11:25 +0000181 goto error;
Guido van Rossum9e896b32000-04-05 20:11:21 +0000182 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000183 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000184 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000185 else if (PyObject_AsCharBuffer(v, &s, &len)) {
186 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000187 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000188 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000189 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000190
Guido van Rossum4c08d552000-03-10 22:55:18 +0000191 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000192 while (*s && isspace(Py_CHARMASK(*s)))
193 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000194 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000195 PyErr_SetString(PyExc_ValueError, "empty string for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000196 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000197 }
Christian Heimes99170a52007-12-19 02:07:34 +0000198 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000199 /* We don't care about overflow or underflow. If the platform supports
200 * them, infinities and signed zeroes (on underflow) are fine.
201 * However, strtod can return 0 for denormalized numbers, where atof
202 * does not. So (alas!) we special-case a zero result. Note that
203 * whether strtod sets errno on underflow is not defined, so we can't
204 * key off errno.
205 */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000206 PyFPE_START_PROTECT("strtod", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000207 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000208 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000209 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000210 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000211 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000212 if (end > last)
213 end = last;
Christian Heimes99170a52007-12-19 02:07:34 +0000214 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000215 if (end == s) {
Christian Heimes99170a52007-12-19 02:07:34 +0000216 char *p = (char*)sp;
217 int sign = 1;
218
219 if (*p == '-') {
220 sign = -1;
221 p++;
222 }
223 if (*p == '+') {
224 p++;
225 }
226 if (PyOS_strnicmp(p, "inf", 4) == 0) {
227 return PyFloat_FromDouble(sign * Py_HUGE_VAL);
228 }
229#ifdef Py_NAN
230 if(PyOS_strnicmp(p, "nan", 4) == 0) {
231 return PyFloat_FromDouble(Py_NAN);
232 }
233#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000234 PyOS_snprintf(buffer, sizeof(buffer),
235 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000236 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000237 goto error;
Tim Petersef14d732000-09-23 03:39:17 +0000238 }
239 /* Since end != s, the platform made *some* kind of sense out
240 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000241 while (*end && isspace(Py_CHARMASK(*end)))
242 end++;
243 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000244 PyOS_snprintf(buffer, sizeof(buffer),
245 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000246 PyErr_SetString(PyExc_ValueError, buffer);
Guido van Rossum2be161d2007-05-15 20:43:51 +0000247 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000248 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000249 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000250 PyErr_SetString(PyExc_ValueError,
251 "null byte in argument for float()");
Guido van Rossum2be161d2007-05-15 20:43:51 +0000252 goto error;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000253 }
Tim Petersef14d732000-09-23 03:39:17 +0000254 if (x == 0.0) {
255 /* See above -- may have been strtod being anal
256 about denorms. */
Guido van Rossum2be161d2007-05-15 20:43:51 +0000257 PyFPE_START_PROTECT("atof", goto error)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000258 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000259 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000260 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000261 }
Guido van Rossum2be161d2007-05-15 20:43:51 +0000262 result = PyFloat_FromDouble(x);
263 error:
264 if (s_buffer)
265 PyMem_FREE(s_buffer);
266 return result;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000267}
268
Guido van Rossum234f9421993-06-17 12:35:49 +0000269static void
Fred Drakefd99de62000-07-09 05:02:18 +0000270float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000271{
Guido van Rossum9475a232001-10-05 20:51:39 +0000272 if (PyFloat_CheckExact(op)) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000273 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000274 free_list = op;
275 }
276 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000277 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000278}
279
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000280double
Fred Drakefd99de62000-07-09 05:02:18 +0000281PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000282{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000283 PyNumberMethods *nb;
284 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000285 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000286
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000287 if (op && PyFloat_Check(op))
288 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000289
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000290 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000291 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000292 return -1;
293 }
Tim Petersd2364e82001-11-01 20:09:42 +0000294
Christian Heimes90aa7642007-12-19 02:45:37 +0000295 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000296 PyErr_SetString(PyExc_TypeError, "a float is required");
297 return -1;
298 }
299
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000300 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000301 if (fo == NULL)
302 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000303 if (!PyFloat_Check(fo)) {
304 PyErr_SetString(PyExc_TypeError,
305 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000306 return -1;
307 }
Tim Petersd2364e82001-11-01 20:09:42 +0000308
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000309 val = PyFloat_AS_DOUBLE(fo);
310 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000311
Guido van Rossumb6775db1994-08-01 11:34:53 +0000312 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000313}
314
315/* Methods */
316
Tim Peters97019e42001-11-28 22:43:45 +0000317static void
Neal Norwitz545686b2006-12-28 04:45:06 +0000318format_double(char *buf, size_t buflen, double ob_fval, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000319{
320 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000321 char format[32];
Christian Heimes99170a52007-12-19 02:07:34 +0000322 int i;
323
324 /* Subroutine for float_repr, float_str and float_print.
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000325 We want float numbers to be recognizable as such,
326 i.e., they should contain a decimal point or an exponent.
327 However, %g may print the number as an integer;
328 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000329
Martin v. Löwis737ea822004-06-08 18:52:54 +0000330 PyOS_snprintf(format, 32, "%%.%ig", precision);
Neal Norwitz545686b2006-12-28 04:45:06 +0000331 PyOS_ascii_formatd(buf, buflen, format, ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000332 cp = buf;
333 if (*cp == '-')
334 cp++;
335 for (; *cp != '\0'; cp++) {
336 /* Any non-digit means it's not an integer;
337 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000338 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000339 break;
340 }
341 if (*cp == '\0') {
342 *cp++ = '.';
343 *cp++ = '0';
344 *cp++ = '\0';
Christian Heimes99170a52007-12-19 02:07:34 +0000345 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000346 }
Christian Heimes99170a52007-12-19 02:07:34 +0000347 /* Checking the next three chars should be more than enough to
348 * detect inf or nan, even on Windows. We check for inf or nan
349 * at last because they are rare cases.
350 */
351 for (i=0; *cp != '\0' && i<3; cp++, i++) {
352 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
353 continue;
354 /* found something that is neither a digit nor point
355 * it might be a NaN or INF
356 */
357#ifdef Py_NAN
358 if (Py_IS_NAN(ob_fval)) {
359 strcpy(buf, "nan");
360 }
361 else
362#endif
363 if (Py_IS_INFINITY(ob_fval)) {
364 cp = buf;
365 if (*cp == '-')
366 cp++;
367 strcpy(cp, "inf");
368 }
369 break;
370 }
371
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000372}
373
Neal Norwitz545686b2006-12-28 04:45:06 +0000374static void
375format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Tim Peters97019e42001-11-28 22:43:45 +0000376{
Neal Norwitz545686b2006-12-28 04:45:06 +0000377 assert(PyFloat_Check(v));
378 format_double(buf, buflen, PyFloat_AS_DOUBLE(v), precision);
Tim Peters97019e42001-11-28 22:43:45 +0000379}
380
Christian Heimesb76922a2007-12-11 01:06:40 +0000381#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +0000382/* The following function is based on Tcl_PrintDouble,
383 * from tclUtil.c.
384 */
385
386#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX )
387#define is_nan(d) ((d) != (d))
388
389static void
390format_double_repr(char *dst, double value)
391{
392 char *p, c;
393 int exp;
394 int signum;
395 char buffer[30];
396
397 /*
398 * Handle NaN.
399 */
400
401 if (is_nan(value)) {
402 strcpy(dst, "nan");
403 return;
404 }
405
406 /*
407 * Handle infinities.
408 */
409
410 if (is_infinite(value)) {
411 if (value < 0) {
412 strcpy(dst, "-inf");
413 } else {
414 strcpy(dst, "inf");
415 }
416 return;
417 }
418
419 /*
420 * Ordinary (normal and denormal) values.
421 */
422
423 exp = _PyFloat_Digits(buffer, value, &signum)+1;
424 if (signum) {
425 *dst++ = '-';
426 }
427 p = buffer;
428 if (exp < -3 || exp > 17) {
429 /*
430 * E format for numbers < 1e-3 or >= 1e17.
431 */
432
433 *dst++ = *p++;
434 c = *p;
435 if (c != '\0') {
436 *dst++ = '.';
437 while (c != '\0') {
438 *dst++ = c;
439 c = *++p;
440 }
441 }
442 sprintf(dst, "e%+d", exp-1);
443 } else {
444 /*
445 * F format for others.
446 */
447
448 if (exp <= 0) {
449 *dst++ = '0';
450 }
451 c = *p;
452 while (exp-- > 0) {
453 if (c != '\0') {
454 *dst++ = c;
455 c = *++p;
456 } else {
457 *dst++ = '0';
458 }
459 }
460 *dst++ = '.';
461 if (c == '\0') {
462 *dst++ = '0';
463 } else {
464 while (++exp < 0) {
465 *dst++ = '0';
466 }
467 while (c != '\0') {
468 *dst++ = c;
469 c = *++p;
470 }
471 }
472 *dst++ = '\0';
473 }
474}
475
476static void
477format_float_repr(char *buf, PyFloatObject *v)
478{
479 assert(PyFloat_Check(v));
480 format_double_repr(buf, PyFloat_AS_DOUBLE(v));
481}
482
Christian Heimesb76922a2007-12-11 01:06:40 +0000483#endif /* Py_BROKEN_REPR */
484
Neil Schemenauer32117e52001-01-04 01:44:34 +0000485/* Macro and helper that convert PyObject obj to a C double and store
Neil Schemenauer16c70752007-09-21 20:19:23 +0000486 the value in dbl. If conversion to double raises an exception, obj is
Tim Peters77d8a4f2001-12-11 20:31:34 +0000487 set to NULL, and the function invoking this macro returns NULL. If
488 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
489 stored in obj, and returned from the function invoking this macro.
490*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000491#define CONVERT_TO_DOUBLE(obj, dbl) \
492 if (PyFloat_Check(obj)) \
493 dbl = PyFloat_AS_DOUBLE(obj); \
494 else if (convert_to_double(&(obj), &(dbl)) < 0) \
495 return obj;
496
497static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000498convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000499{
500 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000501
Guido van Rossumddefaf32007-01-14 03:31:43 +0000502 if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000503 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000504 if (*dbl == -1.0 && PyErr_Occurred()) {
505 *v = NULL;
506 return -1;
507 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000508 }
509 else {
510 Py_INCREF(Py_NotImplemented);
511 *v = Py_NotImplemented;
512 return -1;
513 }
514 return 0;
515}
516
Guido van Rossum57072eb1999-12-23 19:00:28 +0000517/* Precisions used by repr() and str(), respectively.
518
519 The repr() precision (17 significant decimal digits) is the minimal number
520 that is guaranteed to have enough precision so that if the number is read
521 back in the exact same binary value is recreated. This is true for IEEE
522 floating point by design, and also happens to work for all other modern
523 hardware.
524
525 The str() precision is chosen so that in most cases, the rounding noise
526 created by various operations is suppressed, while giving plenty of
527 precision for practical use.
528
529*/
530
531#define PREC_REPR 17
532#define PREC_STR 12
533
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000534static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000535float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000536{
Christian Heimesb76922a2007-12-11 01:06:40 +0000537#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +0000538 char buf[30];
539 format_float_repr(buf, v);
Christian Heimesb76922a2007-12-11 01:06:40 +0000540#else
541 char buf[100];
542 format_float(buf, sizeof(buf), v, PREC_REPR);
543#endif
544
Walter Dörwald1ab83302007-05-18 17:15:44 +0000545 return PyUnicode_FromString(buf);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000546}
547
548static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000549float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000550{
551 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000552 format_float(buf, sizeof(buf), v, PREC_STR);
Walter Dörwald7696ed72007-05-31 15:51:35 +0000553 return PyUnicode_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000554}
555
Tim Peters307fa782004-09-23 08:06:40 +0000556/* Comparison is pretty much a nightmare. When comparing float to float,
557 * we do it as straightforwardly (and long-windedly) as conceivable, so
558 * that, e.g., Python x == y delivers the same result as the platform
559 * C x == y when x and/or y is a NaN.
560 * When mixing float with an integer type, there's no good *uniform* approach.
561 * Converting the double to an integer obviously doesn't work, since we
562 * may lose info from fractional bits. Converting the integer to a double
563 * also has two failure modes: (1) a long int may trigger overflow (too
564 * large to fit in the dynamic range of a C double); (2) even a C long may have
565 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
566 * 63 bits of precision, but a C double probably has only 53), and then
567 * we can falsely claim equality when low-order integer bits are lost by
568 * coercion to double. So this part is painful too.
569 */
570
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000571static PyObject*
572float_richcompare(PyObject *v, PyObject *w, int op)
573{
574 double i, j;
575 int r = 0;
576
Tim Peters307fa782004-09-23 08:06:40 +0000577 assert(PyFloat_Check(v));
578 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000579
Tim Peters307fa782004-09-23 08:06:40 +0000580 /* Switch on the type of w. Set i and j to doubles to be compared,
581 * and op to the richcomp to use.
582 */
583 if (PyFloat_Check(w))
584 j = PyFloat_AS_DOUBLE(w);
585
Thomas Wouters477c8d52006-05-27 19:21:47 +0000586 else if (!Py_IS_FINITE(i)) {
Neal Norwitz1fe5f382007-08-31 04:32:55 +0000587 if (PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000588 /* If i is an infinity, its magnitude exceeds any
589 * finite integer, so it doesn't matter which int we
590 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000591 */
592 j = 0.0;
593 else
594 goto Unimplemented;
595 }
596
Tim Peters307fa782004-09-23 08:06:40 +0000597 else if (PyLong_Check(w)) {
598 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
599 int wsign = _PyLong_Sign(w);
600 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000601 int exponent;
602
603 if (vsign != wsign) {
604 /* Magnitudes are irrelevant -- the signs alone
605 * determine the outcome.
606 */
607 i = (double)vsign;
608 j = (double)wsign;
609 goto Compare;
610 }
611 /* The signs are the same. */
612 /* Convert w to a double if it fits. In particular, 0 fits. */
613 nbits = _PyLong_NumBits(w);
614 if (nbits == (size_t)-1 && PyErr_Occurred()) {
615 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000616 * to hold the # of bits. Replace with little doubles
617 * that give the same outcome -- w is so large that
618 * its magnitude must exceed the magnitude of any
619 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000620 */
621 PyErr_Clear();
622 i = (double)vsign;
623 assert(wsign != 0);
624 j = wsign * 2.0;
625 goto Compare;
626 }
627 if (nbits <= 48) {
628 j = PyLong_AsDouble(w);
629 /* It's impossible that <= 48 bits overflowed. */
630 assert(j != -1.0 || ! PyErr_Occurred());
631 goto Compare;
632 }
633 assert(wsign != 0); /* else nbits was 0 */
634 assert(vsign != 0); /* if vsign were 0, then since wsign is
635 * not 0, we would have taken the
636 * vsign != wsign branch at the start */
637 /* We want to work with non-negative numbers. */
638 if (vsign < 0) {
639 /* "Multiply both sides" by -1; this also swaps the
640 * comparator.
641 */
642 i = -i;
643 op = _Py_SwappedOp[op];
644 }
645 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000646 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000647 /* exponent is the # of bits in v before the radix point;
648 * we know that nbits (the # of bits in w) > 48 at this point
649 */
650 if (exponent < 0 || (size_t)exponent < nbits) {
651 i = 1.0;
652 j = 2.0;
653 goto Compare;
654 }
655 if ((size_t)exponent > nbits) {
656 i = 2.0;
657 j = 1.0;
658 goto Compare;
659 }
660 /* v and w have the same number of bits before the radix
661 * point. Construct two longs that have the same comparison
662 * outcome.
663 */
664 {
665 double fracpart;
666 double intpart;
667 PyObject *result = NULL;
668 PyObject *one = NULL;
669 PyObject *vv = NULL;
670 PyObject *ww = w;
671
672 if (wsign < 0) {
673 ww = PyNumber_Negative(w);
674 if (ww == NULL)
675 goto Error;
676 }
677 else
678 Py_INCREF(ww);
679
680 fracpart = modf(i, &intpart);
681 vv = PyLong_FromDouble(intpart);
682 if (vv == NULL)
683 goto Error;
684
685 if (fracpart != 0.0) {
686 /* Shift left, and or a 1 bit into vv
687 * to represent the lost fraction.
688 */
689 PyObject *temp;
690
Christian Heimes217cfd12007-12-02 14:31:20 +0000691 one = PyLong_FromLong(1);
Tim Peters307fa782004-09-23 08:06:40 +0000692 if (one == NULL)
693 goto Error;
694
695 temp = PyNumber_Lshift(ww, one);
696 if (temp == NULL)
697 goto Error;
698 Py_DECREF(ww);
699 ww = temp;
700
701 temp = PyNumber_Lshift(vv, one);
702 if (temp == NULL)
703 goto Error;
704 Py_DECREF(vv);
705 vv = temp;
706
707 temp = PyNumber_Or(vv, one);
708 if (temp == NULL)
709 goto Error;
710 Py_DECREF(vv);
711 vv = temp;
712 }
713
714 r = PyObject_RichCompareBool(vv, ww, op);
715 if (r < 0)
716 goto Error;
717 result = PyBool_FromLong(r);
718 Error:
719 Py_XDECREF(vv);
720 Py_XDECREF(ww);
721 Py_XDECREF(one);
722 return result;
723 }
724 } /* else if (PyLong_Check(w)) */
725
726 else /* w isn't float, int, or long */
727 goto Unimplemented;
728
729 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000730 PyFPE_START_PROTECT("richcompare", return NULL)
731 switch (op) {
732 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000733 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000734 break;
735 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000736 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000737 break;
738 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000739 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000740 break;
741 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000742 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000743 break;
744 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000745 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000746 break;
747 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000748 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000749 break;
750 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000751 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000752 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000753
754 Unimplemented:
755 Py_INCREF(Py_NotImplemented);
756 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000757}
758
Guido van Rossum9bfef441993-03-29 10:43:31 +0000759static long
Fred Drakefd99de62000-07-09 05:02:18 +0000760float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000761{
Tim Peters39dce292000-08-15 03:34:48 +0000762 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000763}
764
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000765static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000766float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000767{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000768 double a,b;
769 CONVERT_TO_DOUBLE(v, a);
770 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000771 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000772 a = a + b;
773 PyFPE_END_PROTECT(a)
774 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000775}
776
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000777static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000778float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000779{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000780 double a,b;
781 CONVERT_TO_DOUBLE(v, a);
782 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000783 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000784 a = a - b;
785 PyFPE_END_PROTECT(a)
786 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000787}
788
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000789static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000790float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000791{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000792 double a,b;
793 CONVERT_TO_DOUBLE(v, a);
794 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000795 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000796 a = a * b;
797 PyFPE_END_PROTECT(a)
798 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000799}
800
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000801static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000802float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000803{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000804 double a,b;
805 CONVERT_TO_DOUBLE(v, a);
806 CONVERT_TO_DOUBLE(w, b);
807 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000808 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000809 return NULL;
810 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000811 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000812 a = a / b;
813 PyFPE_END_PROTECT(a)
814 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000815}
816
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000817static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000818float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000819{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000820 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000821 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000822 CONVERT_TO_DOUBLE(v, vx);
823 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000824 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000825 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000826 return NULL;
827 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000828 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000829 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000830 /* note: checking mod*wx < 0 is incorrect -- underflows to
831 0 if wx < sqrt(smallest nonzero double) */
832 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000833 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000834 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000835 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000836 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000837}
838
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000839static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000840float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000841{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000842 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000843 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000844 CONVERT_TO_DOUBLE(v, vx);
845 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000846 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000847 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000848 return NULL;
849 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000850 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000851 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000852 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000853 exact multiple of wx. But this is fp arithmetic, and fp
854 vx - mod is an approximation; the result is that div may
855 not be an exact integral value after the division, although
856 it will always be very close to one.
857 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000858 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000859 if (mod) {
860 /* ensure the remainder has the same sign as the denominator */
861 if ((wx < 0) != (mod < 0)) {
862 mod += wx;
863 div -= 1.0;
864 }
865 }
866 else {
867 /* the remainder is zero, and in the presence of signed zeroes
868 fmod returns different results across platforms; ensure
869 it has the same sign as the denominator; we'd like to do
870 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000871 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000872 if (wx < 0.0)
873 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000874 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000875 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000876 if (div) {
877 floordiv = floor(div);
878 if (div - floordiv > 0.5)
879 floordiv += 1.0;
880 }
881 else {
882 /* div is zero - get the same sign as the true quotient */
883 div *= div; /* hide "div = +0" from optimizers */
884 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
885 }
886 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000887 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000888}
889
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000890static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000891float_floor_div(PyObject *v, PyObject *w)
892{
893 PyObject *t, *r;
894
895 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000896 if (t == NULL || t == Py_NotImplemented)
897 return t;
898 assert(PyTuple_CheckExact(t));
899 r = PyTuple_GET_ITEM(t, 0);
900 Py_INCREF(r);
901 Py_DECREF(t);
902 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000903}
904
905static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000906float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000907{
908 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000909
910 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000911 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000912 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000913 return NULL;
914 }
915
Neil Schemenauer32117e52001-01-04 01:44:34 +0000916 CONVERT_TO_DOUBLE(v, iv);
917 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000918
919 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000920 if (iw == 0) { /* v**0 is 1, even 0**0 */
Guido van Rossum360e4b82007-05-14 22:51:27 +0000921 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +0000922 }
Tim Peters96685bf2001-08-23 22:31:37 +0000923 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000924 if (iw < 0.0) {
925 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000926 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000927 return NULL;
928 }
929 return PyFloat_FromDouble(0.0);
930 }
Tim Peterse87568d2003-05-24 20:18:24 +0000931 if (iv < 0.0) {
932 /* Whether this is an error is a mess, and bumps into libm
933 * bugs so we have to figure it out ourselves.
934 */
935 if (iw != floor(iw)) {
Jeffrey Yasskin3404b3c2007-09-07 15:15:49 +0000936 /* Negative numbers raised to fractional powers
937 * become complex.
938 */
939 return PyComplex_Type.tp_as_number->nb_power(v, w, z);
Tim Peterse87568d2003-05-24 20:18:24 +0000940 }
941 /* iw is an exact integer, albeit perhaps a very large one.
942 * -1 raised to an exact integer should never be exceptional.
943 * Alas, some libms (chiefly glibc as of early 2003) return
944 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
945 * happen to be representable in a *C* integer. That's a
946 * bug; we let that slide in math.pow() (which currently
947 * reflects all platform accidents), but not for Python's **.
948 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000949 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +0000950 /* Return 1 if iw is even, -1 if iw is odd; there's
951 * no guarantee that any C integral type is big
952 * enough to hold iw, so we have to check this
953 * indirectly.
954 */
955 ix = floor(iw * 0.5) * 2.0;
956 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
957 }
958 /* Else iv != -1.0, and overflow or underflow are possible.
959 * Unless we're to write pow() ourselves, we have to trust
960 * the platform to do this correctly.
961 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000962 }
Tim Peters96685bf2001-08-23 22:31:37 +0000963 errno = 0;
964 PyFPE_START_PROTECT("pow", return NULL)
965 ix = pow(iv, iw);
966 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000967 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000968 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000969 /* We don't expect any errno value other than ERANGE, but
970 * the range of libm bugs appears unbounded.
971 */
972 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
973 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000974 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000975 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000976 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000977}
978
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000979static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000980float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000981{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000982 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000983}
984
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000985static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000986float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000987{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000988 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000989}
990
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000991static int
Jack Diederich4dafcc42006-11-28 19:15:13 +0000992float_bool(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000993{
994 return v->ob_fval != 0.0;
995}
996
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000997static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +0000998float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000999{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001000 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001001 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001002
1003 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001004 /* Try to get out cheap if this fits in a Python int. The attempt
1005 * to cast to long must be protected, as C doesn't define what
1006 * happens if the double is too big to fit in a long. Some rare
1007 * systems raise an exception then (RISCOS was mentioned as one,
1008 * and someone using a non-default option on Sun also bumped into
1009 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1010 * still be vulnerable: if a long has more bits of precision than
1011 * a double, casting MIN/MAX to double may yield an approximation,
1012 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1013 * yield true from the C expression wholepart<=LONG_MAX, despite
1014 * that wholepart is actually greater than LONG_MAX.
1015 */
1016 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1017 const long aslong = (long)wholepart;
Christian Heimes217cfd12007-12-02 14:31:20 +00001018 return PyLong_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001019 }
1020 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001021}
1022
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001023static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001024float_round(PyObject *v, PyObject *args)
1025{
1026#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
1027 double x;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001028 double f = 1.0;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001029 double flr, cil;
1030 double rounded;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001031 int ndigits = UNDEF_NDIGITS;
1032
1033 if (!PyArg_ParseTuple(args, "|i", &ndigits))
1034 return NULL;
1035
1036 x = PyFloat_AsDouble(v);
1037
1038 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001039 f = pow(10.0, ndigits);
1040 x *= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001041 }
1042
1043 flr = floor(x);
1044 cil = ceil(x);
1045
1046 if (x-flr > 0.5)
1047 rounded = cil;
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001048 else if (x-flr == 0.5)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001049 rounded = fmod(flr, 2) == 0 ? flr : cil;
1050 else
1051 rounded = flr;
1052
1053 if (ndigits != UNDEF_NDIGITS) {
Guido van Rossum6deb1bf2007-08-31 00:27:03 +00001054 rounded /= f;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001055 return PyFloat_FromDouble(rounded);
1056 }
1057
1058 return PyLong_FromDouble(rounded);
1059#undef UNDEF_NDIGITS
1060}
1061
1062static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001063float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001064{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001065 if (PyFloat_CheckExact(v))
1066 Py_INCREF(v);
1067 else
1068 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001069 return v;
1070}
1071
Christian Heimes26855632008-01-27 23:50:43 +00001072static PyObject *
Christian Heimes292d3512008-02-03 16:51:08 +00001073float_as_integer_ratio(PyObject *v, PyObject *unused)
Christian Heimes26855632008-01-27 23:50:43 +00001074{
1075 double self;
1076 double float_part;
1077 int exponent;
Christian Heimes292d3512008-02-03 16:51:08 +00001078 int i;
1079
Christian Heimes26855632008-01-27 23:50:43 +00001080 PyObject *prev;
Christian Heimes26855632008-01-27 23:50:43 +00001081 PyObject *py_exponent = NULL;
1082 PyObject *numerator = NULL;
1083 PyObject *denominator = NULL;
1084 PyObject *result_pair = NULL;
Christian Heimes292d3512008-02-03 16:51:08 +00001085 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Christian Heimes26855632008-01-27 23:50:43 +00001086
1087#define INPLACE_UPDATE(obj, call) \
1088 prev = obj; \
1089 obj = call; \
1090 Py_DECREF(prev); \
1091
1092 CONVERT_TO_DOUBLE(v, self);
1093
1094 if (Py_IS_INFINITY(self)) {
1095 PyErr_SetString(PyExc_OverflowError,
1096 "Cannot pass infinity to float.as_integer_ratio.");
1097 return NULL;
1098 }
1099#ifdef Py_NAN
1100 if (Py_IS_NAN(self)) {
1101 PyErr_SetString(PyExc_ValueError,
1102 "Cannot pass nan to float.as_integer_ratio.");
1103 return NULL;
1104 }
1105#endif
1106
Christian Heimes26855632008-01-27 23:50:43 +00001107 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Christian Heimes292d3512008-02-03 16:51:08 +00001108 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Christian Heimes26855632008-01-27 23:50:43 +00001109 PyFPE_END_PROTECT(float_part);
Christian Heimes292d3512008-02-03 16:51:08 +00001110
1111 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
1112 float_part *= 2.0;
1113 exponent--;
1114 }
1115 /* self == float_part * 2**exponent exactly and float_part is integral.
1116 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1117 to be truncated by PyLong_FromDouble(). */
Christian Heimes26855632008-01-27 23:50:43 +00001118
Christian Heimes292d3512008-02-03 16:51:08 +00001119 numerator = PyLong_FromDouble(float_part);
Christian Heimes26855632008-01-27 23:50:43 +00001120 if (numerator == NULL) goto error;
1121
Christian Heimes292d3512008-02-03 16:51:08 +00001122 /* fold in 2**exponent */
Christian Heimes26855632008-01-27 23:50:43 +00001123 denominator = PyLong_FromLong(1);
Christian Heimes292d3512008-02-03 16:51:08 +00001124 py_exponent = PyLong_FromLong(labs((long)exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001125 if (py_exponent == NULL) goto error;
1126 INPLACE_UPDATE(py_exponent,
1127 long_methods->nb_lshift(denominator, py_exponent));
1128 if (py_exponent == NULL) goto error;
1129 if (exponent > 0) {
1130 INPLACE_UPDATE(numerator,
Christian Heimes292d3512008-02-03 16:51:08 +00001131 long_methods->nb_multiply(numerator, py_exponent));
Christian Heimes26855632008-01-27 23:50:43 +00001132 if (numerator == NULL) goto error;
1133 }
1134 else {
1135 Py_DECREF(denominator);
1136 denominator = py_exponent;
1137 py_exponent = NULL;
1138 }
1139
Christian Heimes292d3512008-02-03 16:51:08 +00001140 /* Returns ints instead of longs where possible */
1141 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1142 if (numerator == NULL) goto error;
1143 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1144 if (denominator == NULL) goto error;
1145
Christian Heimes26855632008-01-27 23:50:43 +00001146 result_pair = PyTuple_Pack(2, numerator, denominator);
1147
1148#undef INPLACE_UPDATE
1149error:
1150 Py_XDECREF(py_exponent);
Christian Heimes26855632008-01-27 23:50:43 +00001151 Py_XDECREF(denominator);
1152 Py_XDECREF(numerator);
1153 return result_pair;
1154}
1155
1156PyDoc_STRVAR(float_as_integer_ratio_doc,
1157"float.as_integer_ratio() -> (int, int)\n"
1158"\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001159"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1160"float and with a positive denominator.\n"
1161"Raises OverflowError on infinities and a ValueError on nans.\n"
Christian Heimes26855632008-01-27 23:50:43 +00001162"\n"
1163">>> (10.0).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001164"(10, 1)\n"
Christian Heimes26855632008-01-27 23:50:43 +00001165">>> (0.0).as_integer_ratio()\n"
1166"(0, 1)\n"
1167">>> (-.25).as_integer_ratio()\n"
Christian Heimes292d3512008-02-03 16:51:08 +00001168"(-1, 4)");
Christian Heimes26855632008-01-27 23:50:43 +00001169
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001170
Jeremy Hylton938ace62002-07-17 16:30:39 +00001171static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001172float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1173
Tim Peters6d6c1a32001-08-02 04:15:00 +00001174static PyObject *
1175float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1176{
1177 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001178 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001179
Guido van Rossumbef14172001-08-29 15:47:46 +00001180 if (type != &PyFloat_Type)
1181 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001182 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1183 return NULL;
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001184 if (PyUnicode_Check(x))
Georg Brandl428f0642007-03-18 18:35:15 +00001185 return PyFloat_FromString(x);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001186 return PyNumber_Float(x);
1187}
1188
Guido van Rossumbef14172001-08-29 15:47:46 +00001189/* Wimpy, slow approach to tp_new calls for subtypes of float:
1190 first create a regular float from whatever arguments we got,
1191 then allocate a subtype instance and initialize its ob_fval
1192 from the regular float. The regular float is then thrown away.
1193*/
1194static PyObject *
1195float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1196{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001197 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001198
1199 assert(PyType_IsSubtype(type, &PyFloat_Type));
1200 tmp = float_new(&PyFloat_Type, args, kwds);
1201 if (tmp == NULL)
1202 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001203 assert(PyFloat_CheckExact(tmp));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001204 newobj = type->tp_alloc(type, 0);
1205 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001206 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001207 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001208 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001209 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001210 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001211 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001212}
1213
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001214static PyObject *
1215float_getnewargs(PyFloatObject *v)
1216{
1217 return Py_BuildValue("(d)", v->ob_fval);
1218}
1219
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001220/* this is for the benefit of the pack/unpack routines below */
1221
1222typedef enum {
1223 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1224} float_format_type;
1225
1226static float_format_type double_format, float_format;
1227static float_format_type detected_double_format, detected_float_format;
1228
1229static PyObject *
1230float_getformat(PyTypeObject *v, PyObject* arg)
1231{
1232 char* s;
1233 float_format_type r;
1234
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001235 if (!PyUnicode_Check(arg)) {
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001236 PyErr_Format(PyExc_TypeError,
1237 "__getformat__() argument must be string, not %.500s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001238 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001239 return NULL;
1240 }
Neal Norwitz6ea45d32007-08-26 04:19:43 +00001241 s = PyUnicode_AsString(arg);
1242 if (s == NULL)
1243 return NULL;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001244 if (strcmp(s, "double") == 0) {
1245 r = double_format;
1246 }
1247 else if (strcmp(s, "float") == 0) {
1248 r = float_format;
1249 }
1250 else {
1251 PyErr_SetString(PyExc_ValueError,
1252 "__getformat__() argument 1 must be "
1253 "'double' or 'float'");
1254 return NULL;
1255 }
1256
1257 switch (r) {
1258 case unknown_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001259 return PyUnicode_FromString("unknown");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001260 case ieee_little_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001261 return PyUnicode_FromString("IEEE, little-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001262 case ieee_big_endian_format:
Walter Dörwald71044582007-06-22 12:26:52 +00001263 return PyUnicode_FromString("IEEE, big-endian");
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001264 default:
1265 Py_FatalError("insane float_format or double_format");
1266 return NULL;
1267 }
1268}
1269
1270PyDoc_STRVAR(float_getformat_doc,
1271"float.__getformat__(typestr) -> string\n"
1272"\n"
1273"You probably don't want to use this function. It exists mainly to be\n"
1274"used in Python's test suite.\n"
1275"\n"
1276"typestr must be 'double' or 'float'. This function returns whichever of\n"
1277"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1278"format of floating point numbers used by the C type named by typestr.");
1279
1280static PyObject *
1281float_setformat(PyTypeObject *v, PyObject* args)
1282{
1283 char* typestr;
1284 char* format;
1285 float_format_type f;
1286 float_format_type detected;
1287 float_format_type *p;
1288
1289 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1290 return NULL;
1291
1292 if (strcmp(typestr, "double") == 0) {
1293 p = &double_format;
1294 detected = detected_double_format;
1295 }
1296 else if (strcmp(typestr, "float") == 0) {
1297 p = &float_format;
1298 detected = detected_float_format;
1299 }
1300 else {
1301 PyErr_SetString(PyExc_ValueError,
1302 "__setformat__() argument 1 must "
1303 "be 'double' or 'float'");
1304 return NULL;
1305 }
1306
1307 if (strcmp(format, "unknown") == 0) {
1308 f = unknown_format;
1309 }
1310 else if (strcmp(format, "IEEE, little-endian") == 0) {
1311 f = ieee_little_endian_format;
1312 }
1313 else if (strcmp(format, "IEEE, big-endian") == 0) {
1314 f = ieee_big_endian_format;
1315 }
1316 else {
1317 PyErr_SetString(PyExc_ValueError,
1318 "__setformat__() argument 2 must be "
1319 "'unknown', 'IEEE, little-endian' or "
1320 "'IEEE, big-endian'");
1321 return NULL;
1322
1323 }
1324
1325 if (f != unknown_format && f != detected) {
1326 PyErr_Format(PyExc_ValueError,
1327 "can only set %s format to 'unknown' or the "
1328 "detected platform value", typestr);
1329 return NULL;
1330 }
1331
1332 *p = f;
1333 Py_RETURN_NONE;
1334}
1335
1336PyDoc_STRVAR(float_setformat_doc,
1337"float.__setformat__(typestr, fmt) -> None\n"
1338"\n"
1339"You probably don't want to use this function. It exists mainly to be\n"
1340"used in Python's test suite.\n"
1341"\n"
1342"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1343"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1344"one of the latter two if it appears to match the underlying C reality.\n"
1345"\n"
1346"Overrides the automatic determination of C-level floating point type.\n"
1347"This affects how floats are converted to and from binary strings.");
1348
Guido van Rossumb43daf72007-08-01 18:08:08 +00001349static PyObject *
1350float_getzero(PyObject *v, void *closure)
1351{
1352 return PyFloat_FromDouble(0.0);
1353}
1354
Eric Smith8c663262007-08-25 02:26:07 +00001355static PyObject *
1356float__format__(PyObject *self, PyObject *args)
1357{
1358 /* when back porting this to 2.6, check type of the format_spec
1359 and call either unicode_long__format__ or
1360 string_long__format__ */
1361 return unicode_float__format__(self, args);
1362}
1363
1364PyDoc_STRVAR(float__format__doc,
1365"float.__format__(format_spec) -> string\n"
1366"\n"
1367"Formats the float according to format_spec.");
1368
1369
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001370static PyMethodDef float_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00001371 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1372 "Returns self, the complex conjugate of any float."},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001373 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1374 "Returns the Integral closest to x between 0 and x."},
1375 {"__round__", (PyCFunction)float_round, METH_VARARGS,
1376 "Returns the Integral closest to x, rounding half toward even.\n"
1377 "When an argument is passed, works like built-in round(x, ndigits)."},
Christian Heimes26855632008-01-27 23:50:43 +00001378 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1379 float_as_integer_ratio_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001380 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001381 {"__getformat__", (PyCFunction)float_getformat,
1382 METH_O|METH_CLASS, float_getformat_doc},
1383 {"__setformat__", (PyCFunction)float_setformat,
1384 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smith8c663262007-08-25 02:26:07 +00001385 {"__format__", (PyCFunction)float__format__,
1386 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001387 {NULL, NULL} /* sentinel */
1388};
1389
Guido van Rossumb43daf72007-08-01 18:08:08 +00001390static PyGetSetDef float_getset[] = {
1391 {"real",
1392 (getter)float_float, (setter)NULL,
1393 "the real part of a complex number",
1394 NULL},
1395 {"imag",
1396 (getter)float_getzero, (setter)NULL,
1397 "the imaginary part of a complex number",
1398 NULL},
1399 {NULL} /* Sentinel */
1400};
1401
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001402PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001403"float(x) -> floating point number\n\
1404\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001405Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001406
1407
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001408static PyNumberMethods float_as_number = {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001409 float_add, /*nb_add*/
1410 float_sub, /*nb_subtract*/
1411 float_mul, /*nb_multiply*/
1412 float_rem, /*nb_remainder*/
1413 float_divmod, /*nb_divmod*/
1414 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001415 (unaryfunc)float_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00001416 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001417 (unaryfunc)float_abs, /*nb_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00001418 (inquiry)float_bool, /*nb_bool*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001419 0, /*nb_invert*/
1420 0, /*nb_lshift*/
1421 0, /*nb_rshift*/
1422 0, /*nb_and*/
1423 0, /*nb_xor*/
1424 0, /*nb_or*/
Neil Schemenauer16c70752007-09-21 20:19:23 +00001425 0, /*nb_reserved*/
Guido van Rossum2fa33db2007-08-23 22:07:24 +00001426 float_trunc, /*nb_int*/
1427 float_trunc, /*nb_long*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001428 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001429 0, /* nb_oct */
1430 0, /* nb_hex */
1431 0, /* nb_inplace_add */
1432 0, /* nb_inplace_subtract */
1433 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00001434 0, /* nb_inplace_remainder */
1435 0, /* nb_inplace_power */
1436 0, /* nb_inplace_lshift */
1437 0, /* nb_inplace_rshift */
1438 0, /* nb_inplace_and */
1439 0, /* nb_inplace_xor */
1440 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001441 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001442 float_div, /* nb_true_divide */
1443 0, /* nb_inplace_floor_divide */
1444 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001445};
1446
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001447PyTypeObject PyFloat_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001448 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001449 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001450 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001451 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001452 (destructor)float_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00001453 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001454 0, /* tp_getattr */
1455 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001456 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001457 (reprfunc)float_repr, /* tp_repr */
1458 &float_as_number, /* tp_as_number */
1459 0, /* tp_as_sequence */
1460 0, /* tp_as_mapping */
1461 (hashfunc)float_hash, /* tp_hash */
1462 0, /* tp_call */
1463 (reprfunc)float_str, /* tp_str */
1464 PyObject_GenericGetAttr, /* tp_getattro */
1465 0, /* tp_setattro */
1466 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001467 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001468 float_doc, /* tp_doc */
1469 0, /* tp_traverse */
1470 0, /* tp_clear */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001471 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001472 0, /* tp_weaklistoffset */
1473 0, /* tp_iter */
1474 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001475 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001476 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00001477 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001478 0, /* tp_base */
1479 0, /* tp_dict */
1480 0, /* tp_descr_get */
1481 0, /* tp_descr_set */
1482 0, /* tp_dictoffset */
1483 0, /* tp_init */
1484 0, /* tp_alloc */
1485 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001486};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001487
1488void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001489_PyFloat_Init(void)
1490{
1491 /* We attempt to determine if this machine is using IEEE
1492 floating point formats by peering at the bits of some
1493 carefully chosen values. If it looks like we are on an
1494 IEEE platform, the float packing/unpacking routines can
1495 just copy bits, if not they resort to arithmetic & shifts
1496 and masks. The shifts & masks approach works on all finite
1497 values, but what happens to infinities, NaNs and signed
1498 zeroes on packing is an accident, and attempting to unpack
1499 a NaN or an infinity will raise an exception.
1500
1501 Note that if we're on some whacked-out platform which uses
1502 IEEE formats but isn't strictly little-endian or big-
1503 endian, we will fall back to the portable shifts & masks
1504 method. */
1505
1506#if SIZEOF_DOUBLE == 8
1507 {
1508 double x = 9006104071832581.0;
1509 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1510 detected_double_format = ieee_big_endian_format;
1511 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1512 detected_double_format = ieee_little_endian_format;
1513 else
1514 detected_double_format = unknown_format;
1515 }
1516#else
1517 detected_double_format = unknown_format;
1518#endif
1519
1520#if SIZEOF_FLOAT == 4
1521 {
1522 float y = 16711938.0;
1523 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1524 detected_float_format = ieee_big_endian_format;
1525 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1526 detected_float_format = ieee_little_endian_format;
1527 else
1528 detected_float_format = unknown_format;
1529 }
1530#else
1531 detected_float_format = unknown_format;
1532#endif
1533
1534 double_format = detected_double_format;
1535 float_format = detected_float_format;
Christian Heimesb76922a2007-12-11 01:06:40 +00001536
1537#ifdef Py_BROKEN_REPR
Christian Heimes827b35c2007-12-10 22:19:17 +00001538 /* Initialize floating point repr */
1539 _PyFloat_DigitsInit();
Christian Heimesb76922a2007-12-11 01:06:40 +00001540#endif
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001541 /* Init float info */
1542 if (FloatInfoType.tp_name == 0)
1543 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001544}
1545
1546void
Christian Heimes15ebc882008-02-04 18:48:49 +00001547PyFloat_CompactFreeList(size_t *pbc, size_t *pbf, size_t *bsum)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001548{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001549 PyFloatObject *p;
1550 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001551 unsigned i;
Christian Heimes15ebc882008-02-04 18:48:49 +00001552 size_t bc = 0, bf = 0; /* block count, number of freed blocks */
1553 size_t fsum = 0; /* total unfreed ints */
1554 int frem; /* remaining unfreed ints per block */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001555
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001556 list = block_list;
1557 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001558 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001559 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001560 bc++;
1561 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001562 for (i = 0, p = &list->objects[0];
1563 i < N_FLOATOBJECTS;
1564 i++, p++) {
Christian Heimes90aa7642007-12-19 02:45:37 +00001565 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001566 frem++;
1567 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001568 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001569 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001570 list->next = block_list;
1571 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001572 for (i = 0, p = &list->objects[0];
1573 i < N_FLOATOBJECTS;
1574 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001575 if (!PyFloat_CheckExact(p) ||
Christian Heimes90aa7642007-12-19 02:45:37 +00001576 Py_REFCNT(p) == 0) {
1577 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001578 free_list;
1579 free_list = p;
1580 }
1581 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001582 }
1583 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001584 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001585 bf++;
1586 }
1587 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001588 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001589 }
Christian Heimes15ebc882008-02-04 18:48:49 +00001590 *pbc = bc;
1591 *pbf = bf;
1592 *bsum = fsum;
1593}
1594
1595void
1596PyFloat_Fini(void)
1597{
1598 PyFloatObject *p;
1599 PyFloatBlock *list;
1600 unsigned i;
1601 size_t bc, bf; /* block count, number of freed blocks */
1602 size_t fsum; /* total unfreed floats per block */
1603
1604 PyFloat_CompactFreeList(&bc, &bf, &fsum);
1605
Guido van Rossum3fce8831999-03-12 19:43:17 +00001606 if (!Py_VerboseFlag)
1607 return;
1608 fprintf(stderr, "# cleanup floats");
1609 if (!fsum) {
1610 fprintf(stderr, "\n");
1611 }
1612 else {
1613 fprintf(stderr,
Christian Heimesba4af492008-03-28 00:55:15 +00001614 ": %" PY_FORMAT_SIZE_T "d unfreed float%s in %"
Christian Heimes15ebc882008-02-04 18:48:49 +00001615 PY_FORMAT_SIZE_T "d out of %"
1616 PY_FORMAT_SIZE_T "d block%s\n",
Guido van Rossum3fce8831999-03-12 19:43:17 +00001617 fsum, fsum == 1 ? "" : "s",
1618 bc - bf, bc, bc == 1 ? "" : "s");
1619 }
1620 if (Py_VerboseFlag > 1) {
1621 list = block_list;
1622 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001623 for (i = 0, p = &list->objects[0];
1624 i < N_FLOATOBJECTS;
1625 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001626 if (PyFloat_CheckExact(p) &&
Christian Heimes90aa7642007-12-19 02:45:37 +00001627 Py_REFCNT(p) != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001628 char buf[100];
Neal Norwitz545686b2006-12-28 04:45:06 +00001629 format_float(buf, sizeof(buf), p, PREC_STR);
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001630 /* XXX(twouters) cast refcount to
1631 long until %zd is universally
1632 available
1633 */
Guido van Rossum3fce8831999-03-12 19:43:17 +00001634 fprintf(stderr,
Thomas Wouters8b87a0b2006-03-01 05:41:20 +00001635 "# <float at %p, refcnt=%ld, val=%s>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +00001636 p, (long)Py_REFCNT(p), buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +00001637 }
1638 }
1639 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001640 }
1641 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001642}
Tim Peters9905b942003-03-20 20:53:32 +00001643
1644/*----------------------------------------------------------------------------
1645 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
Tim Peters9905b942003-03-20 20:53:32 +00001646 */
1647int
1648_PyFloat_Pack4(double x, unsigned char *p, int le)
1649{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001650 if (float_format == unknown_format) {
1651 unsigned char sign;
1652 int e;
1653 double f;
1654 unsigned int fbits;
1655 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001656
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001657 if (le) {
1658 p += 3;
1659 incr = -1;
1660 }
Tim Peters9905b942003-03-20 20:53:32 +00001661
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001662 if (x < 0) {
1663 sign = 1;
1664 x = -x;
1665 }
1666 else
1667 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001668
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001669 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001670
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001671 /* Normalize f to be in the range [1.0, 2.0) */
1672 if (0.5 <= f && f < 1.0) {
1673 f *= 2.0;
1674 e--;
1675 }
1676 else if (f == 0.0)
1677 e = 0;
1678 else {
1679 PyErr_SetString(PyExc_SystemError,
1680 "frexp() result out of range");
1681 return -1;
1682 }
1683
1684 if (e >= 128)
1685 goto Overflow;
1686 else if (e < -126) {
1687 /* Gradual underflow */
1688 f = ldexp(f, 126 + e);
1689 e = 0;
1690 }
1691 else if (!(e == 0 && f == 0.0)) {
1692 e += 127;
1693 f -= 1.0; /* Get rid of leading 1 */
1694 }
1695
1696 f *= 8388608.0; /* 2**23 */
1697 fbits = (unsigned int)(f + 0.5); /* Round */
1698 assert(fbits <= 8388608);
1699 if (fbits >> 23) {
1700 /* The carry propagated out of a string of 23 1 bits. */
1701 fbits = 0;
1702 ++e;
1703 if (e >= 255)
1704 goto Overflow;
1705 }
1706
1707 /* First byte */
1708 *p = (sign << 7) | (e >> 1);
1709 p += incr;
1710
1711 /* Second byte */
1712 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1713 p += incr;
1714
1715 /* Third byte */
1716 *p = (fbits >> 8) & 0xFF;
1717 p += incr;
1718
1719 /* Fourth byte */
1720 *p = fbits & 0xFF;
1721
1722 /* Done */
1723 return 0;
1724
Tim Peters9905b942003-03-20 20:53:32 +00001725 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001726 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001727 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001728 const char *s = (char*)&y;
1729 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001730
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001731 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
1732 goto Overflow;
1733
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001734 if ((float_format == ieee_little_endian_format && !le)
1735 || (float_format == ieee_big_endian_format && le)) {
1736 p += 3;
1737 incr = -1;
1738 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001739
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001740 for (i = 0; i < 4; i++) {
1741 *p = *s++;
1742 p += incr;
1743 }
1744 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001745 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001746 Overflow:
1747 PyErr_SetString(PyExc_OverflowError,
1748 "float too large to pack with f format");
1749 return -1;
Tim Peters9905b942003-03-20 20:53:32 +00001750}
1751
1752int
1753_PyFloat_Pack8(double x, unsigned char *p, int le)
1754{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001755 if (double_format == unknown_format) {
1756 unsigned char sign;
1757 int e;
1758 double f;
1759 unsigned int fhi, flo;
1760 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001761
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001762 if (le) {
1763 p += 7;
1764 incr = -1;
1765 }
Tim Peters9905b942003-03-20 20:53:32 +00001766
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001767 if (x < 0) {
1768 sign = 1;
1769 x = -x;
1770 }
1771 else
1772 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001773
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001774 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001775
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001776 /* Normalize f to be in the range [1.0, 2.0) */
1777 if (0.5 <= f && f < 1.0) {
1778 f *= 2.0;
1779 e--;
1780 }
1781 else if (f == 0.0)
1782 e = 0;
1783 else {
1784 PyErr_SetString(PyExc_SystemError,
1785 "frexp() result out of range");
1786 return -1;
1787 }
1788
1789 if (e >= 1024)
1790 goto Overflow;
1791 else if (e < -1022) {
1792 /* Gradual underflow */
1793 f = ldexp(f, 1022 + e);
1794 e = 0;
1795 }
1796 else if (!(e == 0 && f == 0.0)) {
1797 e += 1023;
1798 f -= 1.0; /* Get rid of leading 1 */
1799 }
1800
1801 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1802 f *= 268435456.0; /* 2**28 */
1803 fhi = (unsigned int)f; /* Truncate */
1804 assert(fhi < 268435456);
1805
1806 f -= (double)fhi;
1807 f *= 16777216.0; /* 2**24 */
1808 flo = (unsigned int)(f + 0.5); /* Round */
1809 assert(flo <= 16777216);
1810 if (flo >> 24) {
1811 /* The carry propagated out of a string of 24 1 bits. */
1812 flo = 0;
1813 ++fhi;
1814 if (fhi >> 28) {
1815 /* And it also progagated out of the next 28 bits. */
1816 fhi = 0;
1817 ++e;
1818 if (e >= 2047)
1819 goto Overflow;
1820 }
1821 }
1822
1823 /* First byte */
1824 *p = (sign << 7) | (e >> 4);
1825 p += incr;
1826
1827 /* Second byte */
1828 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1829 p += incr;
1830
1831 /* Third byte */
1832 *p = (fhi >> 16) & 0xFF;
1833 p += incr;
1834
1835 /* Fourth byte */
1836 *p = (fhi >> 8) & 0xFF;
1837 p += incr;
1838
1839 /* Fifth byte */
1840 *p = fhi & 0xFF;
1841 p += incr;
1842
1843 /* Sixth byte */
1844 *p = (flo >> 16) & 0xFF;
1845 p += incr;
1846
1847 /* Seventh byte */
1848 *p = (flo >> 8) & 0xFF;
1849 p += incr;
1850
1851 /* Eighth byte */
1852 *p = flo & 0xFF;
1853 p += incr;
1854
1855 /* Done */
1856 return 0;
1857
1858 Overflow:
1859 PyErr_SetString(PyExc_OverflowError,
1860 "float too large to pack with d format");
Tim Peters9905b942003-03-20 20:53:32 +00001861 return -1;
1862 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001863 else {
1864 const char *s = (char*)&x;
1865 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001866
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001867 if ((double_format == ieee_little_endian_format && !le)
1868 || (double_format == ieee_big_endian_format && le)) {
1869 p += 7;
1870 incr = -1;
Tim Peters9905b942003-03-20 20:53:32 +00001871 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001872
1873 for (i = 0; i < 8; i++) {
1874 *p = *s++;
1875 p += incr;
1876 }
1877 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001878 }
Tim Peters9905b942003-03-20 20:53:32 +00001879}
1880
Neal Norwitz545686b2006-12-28 04:45:06 +00001881/* Should only be used by marshal. */
1882int
1883_PyFloat_Repr(double x, char *p, size_t len)
1884{
1885 format_double(p, len, x, PREC_REPR);
1886 return (int)strlen(p);
1887}
1888
Tim Peters9905b942003-03-20 20:53:32 +00001889double
1890_PyFloat_Unpack4(const unsigned char *p, int le)
1891{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001892 if (float_format == unknown_format) {
1893 unsigned char sign;
1894 int e;
1895 unsigned int f;
1896 double x;
1897 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001898
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001899 if (le) {
1900 p += 3;
1901 incr = -1;
1902 }
1903
1904 /* First byte */
1905 sign = (*p >> 7) & 1;
1906 e = (*p & 0x7F) << 1;
1907 p += incr;
1908
1909 /* Second byte */
1910 e |= (*p >> 7) & 1;
1911 f = (*p & 0x7F) << 16;
1912 p += incr;
1913
1914 if (e == 255) {
1915 PyErr_SetString(
1916 PyExc_ValueError,
1917 "can't unpack IEEE 754 special value "
1918 "on non-IEEE platform");
1919 return -1;
1920 }
1921
1922 /* Third byte */
1923 f |= *p << 8;
1924 p += incr;
1925
1926 /* Fourth byte */
1927 f |= *p;
1928
1929 x = (double)f / 8388608.0;
1930
1931 /* XXX This sadly ignores Inf/NaN issues */
1932 if (e == 0)
1933 e = -126;
1934 else {
1935 x += 1.0;
1936 e -= 127;
1937 }
1938 x = ldexp(x, e);
1939
1940 if (sign)
1941 x = -x;
1942
1943 return x;
Tim Peters9905b942003-03-20 20:53:32 +00001944 }
Tim Peters9905b942003-03-20 20:53:32 +00001945 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001946 float x;
1947
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001948 if ((float_format == ieee_little_endian_format && !le)
1949 || (float_format == ieee_big_endian_format && le)) {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001950 char buf[4];
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001951 char *d = &buf[3];
1952 int i;
Tim Peters9905b942003-03-20 20:53:32 +00001953
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001954 for (i = 0; i < 4; i++) {
1955 *d-- = *p++;
1956 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001957 memcpy(&x, buf, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001958 }
1959 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001960 memcpy(&x, p, 4);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001961 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00001962
1963 return x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001964 }
Tim Peters9905b942003-03-20 20:53:32 +00001965}
1966
1967double
1968_PyFloat_Unpack8(const unsigned char *p, int le)
1969{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001970 if (double_format == unknown_format) {
1971 unsigned char sign;
1972 int e;
1973 unsigned int fhi, flo;
1974 double x;
1975 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001976
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001977 if (le) {
1978 p += 7;
1979 incr = -1;
1980 }
1981
1982 /* First byte */
1983 sign = (*p >> 7) & 1;
1984 e = (*p & 0x7F) << 4;
1985
1986 p += incr;
1987
1988 /* Second byte */
1989 e |= (*p >> 4) & 0xF;
1990 fhi = (*p & 0xF) << 24;
1991 p += incr;
1992
1993 if (e == 2047) {
1994 PyErr_SetString(
1995 PyExc_ValueError,
1996 "can't unpack IEEE 754 special value "
1997 "on non-IEEE platform");
1998 return -1.0;
1999 }
2000
2001 /* Third byte */
2002 fhi |= *p << 16;
2003 p += incr;
2004
2005 /* Fourth byte */
2006 fhi |= *p << 8;
2007 p += incr;
2008
2009 /* Fifth byte */
2010 fhi |= *p;
2011 p += incr;
2012
2013 /* Sixth byte */
2014 flo = *p << 16;
2015 p += incr;
2016
2017 /* Seventh byte */
2018 flo |= *p << 8;
2019 p += incr;
2020
2021 /* Eighth byte */
2022 flo |= *p;
2023
2024 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
2025 x /= 268435456.0; /* 2**28 */
2026
2027 if (e == 0)
2028 e = -1022;
2029 else {
2030 x += 1.0;
2031 e -= 1023;
2032 }
2033 x = ldexp(x, e);
2034
2035 if (sign)
2036 x = -x;
2037
2038 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002039 }
Tim Peters9905b942003-03-20 20:53:32 +00002040 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002041 double x;
2042
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002043 if ((double_format == ieee_little_endian_format && !le)
2044 || (double_format == ieee_big_endian_format && le)) {
2045 char buf[8];
2046 char *d = &buf[7];
2047 int i;
2048
2049 for (i = 0; i < 8; i++) {
2050 *d-- = *p++;
2051 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002052 memcpy(&x, buf, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002053 }
2054 else {
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002055 memcpy(&x, p, 8);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00002056 }
Michael W. Hudsonb78a5fc2005-12-05 00:27:49 +00002057
2058 return x;
Tim Peters9905b942003-03-20 20:53:32 +00002059 }
Tim Peters9905b942003-03-20 20:53:32 +00002060}