blob: b832f7a483ea0cffddfba487b153889dae3f79fb [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
Neal Norwitz9fdfaaf2008-03-28 05:34:59 +000013#ifdef HAVE_IEEEFP_H
14#include <ieeefp.h>
15#endif
16
Eric Smitha9f7d622008-02-17 19:46:49 +000017#include "formatter_string.h"
Christian Heimesc94e2b52008-01-14 04:13:37 +000018
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
Neal Norwitz5f95a792008-01-25 08:04:16 +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 Heimese93237d2007-12-19 02:37:44 +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 Heimesdfdfaab2007-12-01 11:20:10 +000062double
63PyFloat_GetMax(void)
64{
65 return DBL_MAX;
66}
67
68double
69PyFloat_GetMin(void)
70{
71 return DBL_MIN;
72}
73
Christian Heimes796fc312008-01-30 18:58:29 +000074static PyTypeObject FloatInfoType = {0, 0, 0, 0, 0, 0};
Christian Heimesc94e2b52008-01-14 04:13:37 +000075
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 Heimesdfdfaab2007-12-01 11:20:10 +0000110PyObject *
111PyFloat_GetInfo(void)
112{
Christian Heimes796fc312008-01-30 18:58:29 +0000113 PyObject* floatinfo;
Christian Heimesc94e2b52008-01-14 04:13:37 +0000114 int pos = 0;
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000115
Christian Heimesc94e2b52008-01-14 04:13:37 +0000116 floatinfo = PyStructSequence_New(&FloatInfoType);
117 if (floatinfo == NULL) {
118 return NULL;
119 }
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000120
Christian Heimesc94e2b52008-01-14 04:13:37 +0000121#define SetIntFlag(flag) \
122 PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
123#define SetDblFlag(flag) \
124 PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
Christian Heimesdfdfaab2007-12-01 11:20:10 +0000125
Christian Heimesc94e2b52008-01-14 04:13:37 +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 Heimesc94e2b52008-01-14 04:13:37 +0000144 return floatinfo;
Christian Heimesdfdfaab2007-12-01 11:20:10 +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 Heimese93237d2007-12-19 02:37:44 +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
Tim Petersef14d732000-09-23 03:39:17 +0000163/**************************************************************************
164RED_FLAG 22-Sep-2000 tim
165PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
166
1671. If v was a regular string, *pend was set to point to its terminating
168 null byte. That's useless (the caller can find that without any
169 help from this function!).
170
1712. If v was a Unicode string, or an object convertible to a character
172 buffer, *pend was set to point into stack trash (the auto temp
173 vector holding the character buffer). That was downright dangerous.
174
175Since we can't change the interface of a public API function, pend is
176still supported but now *officially* useless: if pend is not NULL,
177*pend is set to NULL.
178**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000179PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000180PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000181{
Christian Heimes0a8143f2007-12-18 23:22:54 +0000182 const char *s, *last, *end, *sp;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000183 double x;
Tim Petersef14d732000-09-23 03:39:17 +0000184 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000185#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +0000186 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000187#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000188 Py_ssize_t len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000189
Tim Petersef14d732000-09-23 03:39:17 +0000190 if (pend)
191 *pend = NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000192 if (PyString_Check(v)) {
193 s = PyString_AS_STRING(v);
194 len = PyString_GET_SIZE(v);
195 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000196#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +0000197 else if (PyUnicode_Check(v)) {
Skip Montanaro429433b2006-04-18 00:35:43 +0000198 if (PyUnicode_GET_SIZE(v) >= (Py_ssize_t)sizeof(s_buffer)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +0000199 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +0000200 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +0000201 return NULL;
202 }
Tim Petersef14d732000-09-23 03:39:17 +0000203 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000204 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000205 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000206 NULL))
207 return NULL;
208 s = s_buffer;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000209 len = strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000210 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000211#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000212 else if (PyObject_AsCharBuffer(v, &s, &len)) {
213 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000214 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000215 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000216 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000217
Guido van Rossum4c08d552000-03-10 22:55:18 +0000218 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000219 while (*s && isspace(Py_CHARMASK(*s)))
220 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000221 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000222 PyErr_SetString(PyExc_ValueError, "empty string for float()");
223 return NULL;
224 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000225 sp = s;
Tim Petersef14d732000-09-23 03:39:17 +0000226 /* We don't care about overflow or underflow. If the platform supports
227 * them, infinities and signed zeroes (on underflow) are fine.
228 * However, strtod can return 0 for denormalized numbers, where atof
229 * does not. So (alas!) we special-case a zero result. Note that
230 * whether strtod sets errno on underflow is not defined, so we can't
231 * key off errno.
232 */
Tim Peters858346e2000-09-25 21:01:28 +0000233 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000234 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000235 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000236 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000237 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000238 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000239 if (end > last)
240 end = last;
Christian Heimes0a8143f2007-12-18 23:22:54 +0000241 /* Check for inf and nan. This is done late because it rarely happens. */
Tim Petersef14d732000-09-23 03:39:17 +0000242 if (end == s) {
Christian Heimes0a8143f2007-12-18 23:22:54 +0000243 char *p = (char*)sp;
244 int sign = 1;
245
246 if (*p == '-') {
247 sign = -1;
248 p++;
249 }
250 if (*p == '+') {
251 p++;
252 }
253 if (PyOS_strnicmp(p, "inf", 4) == 0) {
254 return PyFloat_FromDouble(sign * Py_HUGE_VAL);
255 }
256#ifdef Py_NAN
257 if(PyOS_strnicmp(p, "nan", 4) == 0) {
258 return PyFloat_FromDouble(Py_NAN);
259 }
260#endif
Barry Warsawaf8aef92001-11-28 20:52:21 +0000261 PyOS_snprintf(buffer, sizeof(buffer),
262 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000263 PyErr_SetString(PyExc_ValueError, buffer);
264 return NULL;
265 }
266 /* Since end != s, the platform made *some* kind of sense out
267 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000268 while (*end && isspace(Py_CHARMASK(*end)))
269 end++;
270 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000271 PyOS_snprintf(buffer, sizeof(buffer),
272 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000273 PyErr_SetString(PyExc_ValueError, buffer);
274 return NULL;
275 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000276 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000277 PyErr_SetString(PyExc_ValueError,
278 "null byte in argument for float()");
279 return NULL;
280 }
Tim Petersef14d732000-09-23 03:39:17 +0000281 if (x == 0.0) {
282 /* See above -- may have been strtod being anal
283 about denorms. */
Tim Peters858346e2000-09-25 21:01:28 +0000284 PyFPE_START_PROTECT("atof", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000285 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000286 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000287 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000288 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000289 return PyFloat_FromDouble(x);
290}
291
Guido van Rossum234f9421993-06-17 12:35:49 +0000292static void
Fred Drakefd99de62000-07-09 05:02:18 +0000293float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000294{
Guido van Rossum9475a232001-10-05 20:51:39 +0000295 if (PyFloat_CheckExact(op)) {
Christian Heimese93237d2007-12-19 02:37:44 +0000296 Py_TYPE(op) = (struct _typeobject *)free_list;
Guido van Rossum9475a232001-10-05 20:51:39 +0000297 free_list = op;
298 }
299 else
Christian Heimese93237d2007-12-19 02:37:44 +0000300 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000301}
302
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000303double
Fred Drakefd99de62000-07-09 05:02:18 +0000304PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000305{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000306 PyNumberMethods *nb;
307 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000308 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000309
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000310 if (op && PyFloat_Check(op))
311 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000312
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000313 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000314 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000315 return -1;
316 }
Tim Petersd2364e82001-11-01 20:09:42 +0000317
Christian Heimese93237d2007-12-19 02:37:44 +0000318 if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000319 PyErr_SetString(PyExc_TypeError, "a float is required");
320 return -1;
321 }
322
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000323 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000324 if (fo == NULL)
325 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000326 if (!PyFloat_Check(fo)) {
327 PyErr_SetString(PyExc_TypeError,
328 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000329 return -1;
330 }
Tim Petersd2364e82001-11-01 20:09:42 +0000331
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000332 val = PyFloat_AS_DOUBLE(fo);
333 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000334
Guido van Rossumb6775db1994-08-01 11:34:53 +0000335 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000336}
337
338/* Methods */
339
Tim Peters97019e42001-11-28 22:43:45 +0000340static void
341format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000342{
343 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000344 char format[32];
Christian Heimes0a8143f2007-12-18 23:22:54 +0000345 int i;
346
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000347 /* Subroutine for float_repr and float_print.
348 We want float numbers to be recognizable as such,
349 i.e., they should contain a decimal point or an exponent.
350 However, %g may print the number as an integer;
351 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000352
353 assert(PyFloat_Check(v));
Martin v. Löwis737ea822004-06-08 18:52:54 +0000354 PyOS_snprintf(format, 32, "%%.%ig", precision);
355 PyOS_ascii_formatd(buf, buflen, format, v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000356 cp = buf;
357 if (*cp == '-')
358 cp++;
359 for (; *cp != '\0'; cp++) {
360 /* Any non-digit means it's not an integer;
361 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000362 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000363 break;
364 }
365 if (*cp == '\0') {
366 *cp++ = '.';
367 *cp++ = '0';
368 *cp++ = '\0';
Christian Heimes0a8143f2007-12-18 23:22:54 +0000369 return;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000370 }
Christian Heimes0a8143f2007-12-18 23:22:54 +0000371 /* Checking the next three chars should be more than enough to
372 * detect inf or nan, even on Windows. We check for inf or nan
373 * at last because they are rare cases.
374 */
375 for (i=0; *cp != '\0' && i<3; cp++, i++) {
376 if (isdigit(Py_CHARMASK(*cp)) || *cp == '.')
377 continue;
378 /* found something that is neither a digit nor point
379 * it might be a NaN or INF
380 */
381#ifdef Py_NAN
382 if (Py_IS_NAN(v->ob_fval)) {
383 strcpy(buf, "nan");
384 }
385 else
386#endif
387 if (Py_IS_INFINITY(v->ob_fval)) {
388 cp = buf;
389 if (*cp == '-')
390 cp++;
391 strcpy(cp, "inf");
392 }
393 break;
394 }
395
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000396}
397
Tim Peters97019e42001-11-28 22:43:45 +0000398/* XXX PyFloat_AsStringEx should not be a public API function (for one
399 XXX thing, its signature passes a buffer without a length; for another,
400 XXX it isn't useful outside this file).
401*/
402void
403PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
404{
405 format_float(buf, 100, v, precision);
406}
407
Christian Heimesf15c66e2007-12-11 00:54:34 +0000408#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000409/* The following function is based on Tcl_PrintDouble,
410 * from tclUtil.c.
411 */
412
413#define is_infinite(d) ( (d) > DBL_MAX || (d) < -DBL_MAX )
414#define is_nan(d) ((d) != (d))
415
416static void
417format_double_repr(char *dst, double value)
418{
419 char *p, c;
420 int exp;
421 int signum;
422 char buffer[30];
423
424 /*
425 * Handle NaN.
426 */
427
428 if (is_nan(value)) {
429 strcpy(dst, "nan");
430 return;
431 }
432
433 /*
434 * Handle infinities.
435 */
436
437 if (is_infinite(value)) {
438 if (value < 0) {
439 strcpy(dst, "-inf");
440 } else {
441 strcpy(dst, "inf");
442 }
443 return;
444 }
445
446 /*
447 * Ordinary (normal and denormal) values.
448 */
449
450 exp = _PyFloat_Digits(buffer, value, &signum)+1;
451 if (signum) {
452 *dst++ = '-';
453 }
454 p = buffer;
455 if (exp < -3 || exp > 17) {
456 /*
457 * E format for numbers < 1e-3 or >= 1e17.
458 */
459
460 *dst++ = *p++;
461 c = *p;
462 if (c != '\0') {
463 *dst++ = '.';
464 while (c != '\0') {
465 *dst++ = c;
466 c = *++p;
467 }
468 }
469 sprintf(dst, "e%+d", exp-1);
470 } else {
471 /*
472 * F format for others.
473 */
474
475 if (exp <= 0) {
476 *dst++ = '0';
477 }
478 c = *p;
479 while (exp-- > 0) {
480 if (c != '\0') {
481 *dst++ = c;
482 c = *++p;
483 } else {
484 *dst++ = '0';
485 }
486 }
487 *dst++ = '.';
488 if (c == '\0') {
489 *dst++ = '0';
490 } else {
491 while (++exp < 0) {
492 *dst++ = '0';
493 }
494 while (c != '\0') {
495 *dst++ = c;
496 c = *++p;
497 }
498 }
499 *dst++ = '\0';
500 }
501}
502
503static void
504format_float_repr(char *buf, PyFloatObject *v)
505{
506 assert(PyFloat_Check(v));
507 format_double_repr(buf, PyFloat_AS_DOUBLE(v));
508}
509
Christian Heimesf15c66e2007-12-11 00:54:34 +0000510#endif /* Py_BROKEN_REPR */
511
Neil Schemenauer32117e52001-01-04 01:44:34 +0000512/* Macro and helper that convert PyObject obj to a C double and store
513 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000514 slot function. If conversion to double raises an exception, obj is
515 set to NULL, and the function invoking this macro returns NULL. If
516 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
517 stored in obj, and returned from the function invoking this macro.
518*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000519#define CONVERT_TO_DOUBLE(obj, dbl) \
520 if (PyFloat_Check(obj)) \
521 dbl = PyFloat_AS_DOUBLE(obj); \
522 else if (convert_to_double(&(obj), &(dbl)) < 0) \
523 return obj;
524
525static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000526convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000527{
528 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000529
Neil Schemenauer32117e52001-01-04 01:44:34 +0000530 if (PyInt_Check(obj)) {
531 *dbl = (double)PyInt_AS_LONG(obj);
532 }
533 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000534 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000535 if (*dbl == -1.0 && PyErr_Occurred()) {
536 *v = NULL;
537 return -1;
538 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000539 }
540 else {
541 Py_INCREF(Py_NotImplemented);
542 *v = Py_NotImplemented;
543 return -1;
544 }
545 return 0;
546}
547
Guido van Rossum57072eb1999-12-23 19:00:28 +0000548/* Precisions used by repr() and str(), respectively.
549
550 The repr() precision (17 significant decimal digits) is the minimal number
551 that is guaranteed to have enough precision so that if the number is read
552 back in the exact same binary value is recreated. This is true for IEEE
553 floating point by design, and also happens to work for all other modern
554 hardware.
555
556 The str() precision is chosen so that in most cases, the rounding noise
557 created by various operations is suppressed, while giving plenty of
558 precision for practical use.
559
560*/
561
562#define PREC_REPR 17
563#define PREC_STR 12
564
Tim Peters97019e42001-11-28 22:43:45 +0000565/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
566 XXX they pass a char buffer without passing a length.
567*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000568void
Fred Drakefd99de62000-07-09 05:02:18 +0000569PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000570{
Tim Peters97019e42001-11-28 22:43:45 +0000571 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000572}
573
Tim Peters72f98e92001-05-08 15:19:57 +0000574void
575PyFloat_AsReprString(char *buf, PyFloatObject *v)
576{
Tim Peters97019e42001-11-28 22:43:45 +0000577 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000578}
579
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000580/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000581static int
Fred Drakefd99de62000-07-09 05:02:18 +0000582float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000583{
584 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000585 format_float(buf, sizeof(buf), v,
586 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Brett Cannon01531592007-09-17 03:28:34 +0000587 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000588 fputs(buf, fp);
Brett Cannon01531592007-09-17 03:28:34 +0000589 Py_END_ALLOW_THREADS
Guido van Rossum90933611991-06-07 16:10:43 +0000590 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000591}
592
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000593static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000594float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000595{
Christian Heimesf15c66e2007-12-11 00:54:34 +0000596#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +0000597 char buf[30];
598 format_float_repr(buf, v);
Christian Heimesf15c66e2007-12-11 00:54:34 +0000599#else
600 char buf[100];
601 format_float(buf, sizeof(buf), v, PREC_REPR);
602#endif
603
Guido van Rossum57072eb1999-12-23 19:00:28 +0000604 return PyString_FromString(buf);
605}
606
607static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000608float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000609{
610 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000611 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000612 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000613}
614
Tim Peters307fa782004-09-23 08:06:40 +0000615/* Comparison is pretty much a nightmare. When comparing float to float,
616 * we do it as straightforwardly (and long-windedly) as conceivable, so
617 * that, e.g., Python x == y delivers the same result as the platform
618 * C x == y when x and/or y is a NaN.
619 * When mixing float with an integer type, there's no good *uniform* approach.
620 * Converting the double to an integer obviously doesn't work, since we
621 * may lose info from fractional bits. Converting the integer to a double
622 * also has two failure modes: (1) a long int may trigger overflow (too
623 * large to fit in the dynamic range of a C double); (2) even a C long may have
624 * more bits than fit in a C double (e.g., on a a 64-bit box long may have
625 * 63 bits of precision, but a C double probably has only 53), and then
626 * we can falsely claim equality when low-order integer bits are lost by
627 * coercion to double. So this part is painful too.
628 */
629
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000630static PyObject*
631float_richcompare(PyObject *v, PyObject *w, int op)
632{
633 double i, j;
634 int r = 0;
635
Tim Peters307fa782004-09-23 08:06:40 +0000636 assert(PyFloat_Check(v));
637 i = PyFloat_AS_DOUBLE(v);
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000638
Tim Peters307fa782004-09-23 08:06:40 +0000639 /* Switch on the type of w. Set i and j to doubles to be compared,
640 * and op to the richcomp to use.
641 */
642 if (PyFloat_Check(w))
643 j = PyFloat_AS_DOUBLE(w);
644
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +0000645 else if (!Py_IS_FINITE(i)) {
Tim Peters307fa782004-09-23 08:06:40 +0000646 if (PyInt_Check(w) || PyLong_Check(w))
Tim Peterse1c69b32004-09-23 19:22:41 +0000647 /* If i is an infinity, its magnitude exceeds any
648 * finite integer, so it doesn't matter which int we
649 * compare i with. If i is a NaN, similarly.
Tim Peters307fa782004-09-23 08:06:40 +0000650 */
651 j = 0.0;
652 else
653 goto Unimplemented;
654 }
655
656 else if (PyInt_Check(w)) {
657 long jj = PyInt_AS_LONG(w);
658 /* In the worst realistic case I can imagine, C double is a
659 * Cray single with 48 bits of precision, and long has 64
660 * bits.
661 */
Tim Peterse1c69b32004-09-23 19:22:41 +0000662#if SIZEOF_LONG > 6
Tim Peters307fa782004-09-23 08:06:40 +0000663 unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
664 if (abs >> 48) {
665 /* Needs more than 48 bits. Make it take the
666 * PyLong path.
667 */
668 PyObject *result;
669 PyObject *ww = PyLong_FromLong(jj);
670
671 if (ww == NULL)
672 return NULL;
673 result = float_richcompare(v, ww, op);
674 Py_DECREF(ww);
675 return result;
676 }
677#endif
678 j = (double)jj;
679 assert((long)j == jj);
680 }
681
682 else if (PyLong_Check(w)) {
683 int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
684 int wsign = _PyLong_Sign(w);
685 size_t nbits;
Tim Peters307fa782004-09-23 08:06:40 +0000686 int exponent;
687
688 if (vsign != wsign) {
689 /* Magnitudes are irrelevant -- the signs alone
690 * determine the outcome.
691 */
692 i = (double)vsign;
693 j = (double)wsign;
694 goto Compare;
695 }
696 /* The signs are the same. */
697 /* Convert w to a double if it fits. In particular, 0 fits. */
698 nbits = _PyLong_NumBits(w);
699 if (nbits == (size_t)-1 && PyErr_Occurred()) {
700 /* This long is so large that size_t isn't big enough
Tim Peterse1c69b32004-09-23 19:22:41 +0000701 * to hold the # of bits. Replace with little doubles
702 * that give the same outcome -- w is so large that
703 * its magnitude must exceed the magnitude of any
704 * finite float.
Tim Peters307fa782004-09-23 08:06:40 +0000705 */
706 PyErr_Clear();
707 i = (double)vsign;
708 assert(wsign != 0);
709 j = wsign * 2.0;
710 goto Compare;
711 }
712 if (nbits <= 48) {
713 j = PyLong_AsDouble(w);
714 /* It's impossible that <= 48 bits overflowed. */
715 assert(j != -1.0 || ! PyErr_Occurred());
716 goto Compare;
717 }
718 assert(wsign != 0); /* else nbits was 0 */
719 assert(vsign != 0); /* if vsign were 0, then since wsign is
720 * not 0, we would have taken the
721 * vsign != wsign branch at the start */
722 /* We want to work with non-negative numbers. */
723 if (vsign < 0) {
724 /* "Multiply both sides" by -1; this also swaps the
725 * comparator.
726 */
727 i = -i;
728 op = _Py_SwappedOp[op];
729 }
730 assert(i > 0.0);
Neal Norwitzb2da01b2006-01-08 01:11:25 +0000731 (void) frexp(i, &exponent);
Tim Peters307fa782004-09-23 08:06:40 +0000732 /* exponent is the # of bits in v before the radix point;
733 * we know that nbits (the # of bits in w) > 48 at this point
734 */
735 if (exponent < 0 || (size_t)exponent < nbits) {
736 i = 1.0;
737 j = 2.0;
738 goto Compare;
739 }
740 if ((size_t)exponent > nbits) {
741 i = 2.0;
742 j = 1.0;
743 goto Compare;
744 }
745 /* v and w have the same number of bits before the radix
746 * point. Construct two longs that have the same comparison
747 * outcome.
748 */
749 {
750 double fracpart;
751 double intpart;
752 PyObject *result = NULL;
753 PyObject *one = NULL;
754 PyObject *vv = NULL;
755 PyObject *ww = w;
756
757 if (wsign < 0) {
758 ww = PyNumber_Negative(w);
759 if (ww == NULL)
760 goto Error;
761 }
762 else
763 Py_INCREF(ww);
764
765 fracpart = modf(i, &intpart);
766 vv = PyLong_FromDouble(intpart);
767 if (vv == NULL)
768 goto Error;
769
770 if (fracpart != 0.0) {
771 /* Shift left, and or a 1 bit into vv
772 * to represent the lost fraction.
773 */
774 PyObject *temp;
775
776 one = PyInt_FromLong(1);
777 if (one == NULL)
778 goto Error;
779
780 temp = PyNumber_Lshift(ww, one);
781 if (temp == NULL)
782 goto Error;
783 Py_DECREF(ww);
784 ww = temp;
785
786 temp = PyNumber_Lshift(vv, one);
787 if (temp == NULL)
788 goto Error;
789 Py_DECREF(vv);
790 vv = temp;
791
792 temp = PyNumber_Or(vv, one);
793 if (temp == NULL)
794 goto Error;
795 Py_DECREF(vv);
796 vv = temp;
797 }
798
799 r = PyObject_RichCompareBool(vv, ww, op);
800 if (r < 0)
801 goto Error;
802 result = PyBool_FromLong(r);
803 Error:
804 Py_XDECREF(vv);
805 Py_XDECREF(ww);
806 Py_XDECREF(one);
807 return result;
808 }
809 } /* else if (PyLong_Check(w)) */
810
811 else /* w isn't float, int, or long */
812 goto Unimplemented;
813
814 Compare:
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000815 PyFPE_START_PROTECT("richcompare", return NULL)
816 switch (op) {
817 case Py_EQ:
Tim Peters307fa782004-09-23 08:06:40 +0000818 r = i == j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000819 break;
820 case Py_NE:
Tim Peters307fa782004-09-23 08:06:40 +0000821 r = i != j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000822 break;
823 case Py_LE:
Tim Peters307fa782004-09-23 08:06:40 +0000824 r = i <= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000825 break;
826 case Py_GE:
Tim Peters307fa782004-09-23 08:06:40 +0000827 r = i >= j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000828 break;
829 case Py_LT:
Tim Peters307fa782004-09-23 08:06:40 +0000830 r = i < j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000831 break;
832 case Py_GT:
Tim Peters307fa782004-09-23 08:06:40 +0000833 r = i > j;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000834 break;
835 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000836 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000837 return PyBool_FromLong(r);
Tim Peters307fa782004-09-23 08:06:40 +0000838
839 Unimplemented:
840 Py_INCREF(Py_NotImplemented);
841 return Py_NotImplemented;
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000842}
843
Guido van Rossum9bfef441993-03-29 10:43:31 +0000844static long
Fred Drakefd99de62000-07-09 05:02:18 +0000845float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000846{
Tim Peters39dce292000-08-15 03:34:48 +0000847 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000848}
849
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000850static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000851float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000852{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000853 double a,b;
854 CONVERT_TO_DOUBLE(v, a);
855 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000856 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000857 a = a + b;
858 PyFPE_END_PROTECT(a)
859 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000860}
861
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000862static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000863float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000864{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000865 double a,b;
866 CONVERT_TO_DOUBLE(v, a);
867 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000868 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000869 a = a - b;
870 PyFPE_END_PROTECT(a)
871 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000872}
873
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000874static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000875float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000876{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000877 double a,b;
878 CONVERT_TO_DOUBLE(v, a);
879 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000880 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000881 a = a * b;
882 PyFPE_END_PROTECT(a)
883 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000884}
885
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000886static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000887float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000888{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000889 double a,b;
890 CONVERT_TO_DOUBLE(v, a);
891 CONVERT_TO_DOUBLE(w, b);
892 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000893 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000894 return NULL;
895 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000896 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000897 a = a / b;
898 PyFPE_END_PROTECT(a)
899 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000900}
901
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000902static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000903float_classic_div(PyObject *v, PyObject *w)
904{
905 double a,b;
906 CONVERT_TO_DOUBLE(v, a);
907 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000908 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000909 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
910 return NULL;
911 if (b == 0.0) {
912 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
913 return NULL;
914 }
915 PyFPE_START_PROTECT("divide", return 0)
916 a = a / b;
917 PyFPE_END_PROTECT(a)
918 return PyFloat_FromDouble(a);
919}
920
921static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000922float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000923{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000924 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000925 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000926 CONVERT_TO_DOUBLE(v, vx);
927 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000928 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000929 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000930 return NULL;
931 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000932 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000933 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000934 /* note: checking mod*wx < 0 is incorrect -- underflows to
935 0 if wx < sqrt(smallest nonzero double) */
936 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000937 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000938 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000939 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000940 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000941}
942
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000943static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000944float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000945{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000946 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000947 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000948 CONVERT_TO_DOUBLE(v, vx);
949 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000950 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000951 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000952 return NULL;
953 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000954 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000955 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000956 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000957 exact multiple of wx. But this is fp arithmetic, and fp
958 vx - mod is an approximation; the result is that div may
959 not be an exact integral value after the division, although
960 it will always be very close to one.
961 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000962 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000963 if (mod) {
964 /* ensure the remainder has the same sign as the denominator */
965 if ((wx < 0) != (mod < 0)) {
966 mod += wx;
967 div -= 1.0;
968 }
969 }
970 else {
971 /* the remainder is zero, and in the presence of signed zeroes
972 fmod returns different results across platforms; ensure
973 it has the same sign as the denominator; we'd like to do
974 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000975 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000976 if (wx < 0.0)
977 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000978 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000979 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000980 if (div) {
981 floordiv = floor(div);
982 if (div - floordiv > 0.5)
983 floordiv += 1.0;
984 }
985 else {
986 /* div is zero - get the same sign as the true quotient */
987 div *= div; /* hide "div = +0" from optimizers */
988 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
989 }
990 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000991 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000992}
993
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000994static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000995float_floor_div(PyObject *v, PyObject *w)
996{
997 PyObject *t, *r;
998
999 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +00001000 if (t == NULL || t == Py_NotImplemented)
1001 return t;
1002 assert(PyTuple_CheckExact(t));
1003 r = PyTuple_GET_ITEM(t, 0);
1004 Py_INCREF(r);
1005 Py_DECREF(t);
1006 return r;
Tim Peters63a35712001-12-11 19:57:24 +00001007}
1008
1009static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +00001010float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001011{
1012 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +00001013
1014 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +00001015 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +00001016 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +00001017 return NULL;
1018 }
1019
Neil Schemenauer32117e52001-01-04 01:44:34 +00001020 CONVERT_TO_DOUBLE(v, iv);
1021 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +00001022
1023 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +00001024 if (iw == 0) { /* v**0 is 1, even 0**0 */
Neal Norwitz8b267b52007-05-03 07:20:57 +00001025 return PyFloat_FromDouble(1.0);
Tim Petersc54d1902000-10-06 00:36:09 +00001026 }
Tim Peters96685bf2001-08-23 22:31:37 +00001027 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +00001028 if (iw < 0.0) {
1029 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001030 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +00001031 return NULL;
1032 }
1033 return PyFloat_FromDouble(0.0);
1034 }
Tim Peterse87568d2003-05-24 20:18:24 +00001035 if (iv < 0.0) {
1036 /* Whether this is an error is a mess, and bumps into libm
1037 * bugs so we have to figure it out ourselves.
1038 */
1039 if (iw != floor(iw)) {
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +00001040 PyErr_SetString(PyExc_ValueError, "negative number "
1041 "cannot be raised to a fractional power");
1042 return NULL;
Tim Peterse87568d2003-05-24 20:18:24 +00001043 }
1044 /* iw is an exact integer, albeit perhaps a very large one.
1045 * -1 raised to an exact integer should never be exceptional.
1046 * Alas, some libms (chiefly glibc as of early 2003) return
1047 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
1048 * happen to be representable in a *C* integer. That's a
1049 * bug; we let that slide in math.pow() (which currently
1050 * reflects all platform accidents), but not for Python's **.
1051 */
Kristján Valur Jónssonf94323f2006-05-25 15:53:30 +00001052 if (iv == -1.0 && Py_IS_FINITE(iw)) {
Tim Peterse87568d2003-05-24 20:18:24 +00001053 /* Return 1 if iw is even, -1 if iw is odd; there's
1054 * no guarantee that any C integral type is big
1055 * enough to hold iw, so we have to check this
1056 * indirectly.
1057 */
1058 ix = floor(iw * 0.5) * 2.0;
1059 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
1060 }
1061 /* Else iv != -1.0, and overflow or underflow are possible.
1062 * Unless we're to write pow() ourselves, we have to trust
1063 * the platform to do this correctly.
1064 */
Guido van Rossum86c04c21996-08-09 20:50:14 +00001065 }
Tim Peters96685bf2001-08-23 22:31:37 +00001066 errno = 0;
1067 PyFPE_START_PROTECT("pow", return NULL)
1068 ix = pow(iv, iw);
1069 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +00001070 Py_ADJUST_ERANGE1(ix);
Alex Martelli348dc882006-08-23 22:17:59 +00001071 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +00001072 /* We don't expect any errno value other than ERANGE, but
1073 * the range of libm bugs appears unbounded.
1074 */
Alex Martelli348dc882006-08-23 22:17:59 +00001075 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
1076 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001077 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +00001078 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001079 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001080}
1081
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001082static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001083float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001084{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001085 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001086}
1087
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001088static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001089float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +00001090{
Tim Petersfaf0cd22001-11-01 21:51:15 +00001091 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001092}
1093
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001094static int
Fred Drakefd99de62000-07-09 05:02:18 +00001095float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +00001096{
1097 return v->ob_fval != 0.0;
1098}
1099
Guido van Rossum234f9421993-06-17 12:35:49 +00001100static int
Fred Drakefd99de62000-07-09 05:02:18 +00001101float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00001102{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001103 if (PyInt_Check(*pw)) {
1104 long x = PyInt_AsLong(*pw);
1105 *pw = PyFloat_FromDouble((double)x);
1106 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001107 return 0;
1108 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001109 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +00001110 double x = PyLong_AsDouble(*pw);
1111 if (x == -1.0 && PyErr_Occurred())
1112 return -1;
1113 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001114 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00001115 return 0;
1116 }
Guido van Rossum1952e382001-09-19 01:25:16 +00001117 else if (PyFloat_Check(*pw)) {
1118 Py_INCREF(*pv);
1119 Py_INCREF(*pw);
1120 return 0;
1121 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00001122 return 1; /* Can't do it */
1123}
1124
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001125static PyObject *
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001126float_trunc(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001127{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001128 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +00001129 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +00001130
1131 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +00001132 /* Try to get out cheap if this fits in a Python int. The attempt
1133 * to cast to long must be protected, as C doesn't define what
1134 * happens if the double is too big to fit in a long. Some rare
1135 * systems raise an exception then (RISCOS was mentioned as one,
1136 * and someone using a non-default option on Sun also bumped into
1137 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
1138 * still be vulnerable: if a long has more bits of precision than
1139 * a double, casting MIN/MAX to double may yield an approximation,
1140 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
1141 * yield true from the C expression wholepart<=LONG_MAX, despite
1142 * that wholepart is actually greater than LONG_MAX.
1143 */
1144 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
1145 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +00001146 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +00001147 }
1148 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001149}
1150
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001151static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +00001152float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001153{
Brett Cannonc3647ac2005-04-26 03:45:26 +00001154 if (PyFloat_CheckExact(v))
1155 Py_INCREF(v);
1156 else
1157 v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001158 return v;
1159}
1160
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001161static PyObject *
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001162float_as_integer_ratio(PyObject *v, PyObject *unused)
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001163{
1164 double self;
1165 double float_part;
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001166 int exponent;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001167 int i;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001168
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001169 PyObject *prev;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001170 PyObject *py_exponent = NULL;
1171 PyObject *numerator = NULL;
1172 PyObject *denominator = NULL;
1173 PyObject *result_pair = NULL;
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001174 PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001175
1176#define INPLACE_UPDATE(obj, call) \
1177 prev = obj; \
1178 obj = call; \
1179 Py_DECREF(prev); \
1180
1181 CONVERT_TO_DOUBLE(v, self);
1182
1183 if (Py_IS_INFINITY(self)) {
1184 PyErr_SetString(PyExc_OverflowError,
1185 "Cannot pass infinity to float.as_integer_ratio.");
1186 return NULL;
1187 }
1188#ifdef Py_NAN
1189 if (Py_IS_NAN(self)) {
1190 PyErr_SetString(PyExc_ValueError,
1191 "Cannot pass nan to float.as_integer_ratio.");
1192 return NULL;
1193 }
1194#endif
1195
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001196 PyFPE_START_PROTECT("as_integer_ratio", goto error);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001197 float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001198 PyFPE_END_PROTECT(float_part);
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001199
Raymond Hettingerf9859032008-02-01 23:45:44 +00001200 for (i=0; i<300 && float_part != floor(float_part) ; i++) {
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001201 float_part *= 2.0;
1202 exponent--;
Raymond Hettingerf9859032008-02-01 23:45:44 +00001203 }
Raymond Hettinger2d1aa332008-02-02 05:11:40 +00001204 /* self == float_part * 2**exponent exactly and float_part is integral.
1205 If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
1206 to be truncated by PyLong_FromDouble(). */
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001207
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001208 numerator = PyLong_FromDouble(float_part);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001209 if (numerator == NULL) goto error;
1210
Raymond Hettingerf9859032008-02-01 23:45:44 +00001211 /* fold in 2**exponent */
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001212 denominator = PyLong_FromLong(1);
Raymond Hettinger1bcb99a2008-02-01 23:12:19 +00001213 py_exponent = PyLong_FromLong(labs((long)exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001214 if (py_exponent == NULL) goto error;
1215 INPLACE_UPDATE(py_exponent,
1216 long_methods->nb_lshift(denominator, py_exponent));
1217 if (py_exponent == NULL) goto error;
1218 if (exponent > 0) {
1219 INPLACE_UPDATE(numerator,
Raymond Hettingerf9859032008-02-01 23:45:44 +00001220 long_methods->nb_multiply(numerator, py_exponent));
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001221 if (numerator == NULL) goto error;
1222 }
1223 else {
1224 Py_DECREF(denominator);
1225 denominator = py_exponent;
1226 py_exponent = NULL;
1227 }
1228
Raymond Hettingerc9e928a2008-02-01 22:15:52 +00001229 /* Returns ints instead of longs where possible */
1230 INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
1231 if (numerator == NULL) goto error;
1232 INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
1233 if (denominator == NULL) goto error;
1234
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001235 result_pair = PyTuple_Pack(2, numerator, denominator);
1236
1237#undef INPLACE_UPDATE
1238error:
1239 Py_XDECREF(py_exponent);
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001240 Py_XDECREF(denominator);
1241 Py_XDECREF(numerator);
1242 return result_pair;
1243}
1244
1245PyDoc_STRVAR(float_as_integer_ratio_doc,
1246"float.as_integer_ratio() -> (int, int)\n"
1247"\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001248"Returns a pair of integers, whose ratio is exactly equal to the original\n"
1249"float and with a positive denominator.\n"
1250"Raises OverflowError on infinities and a ValueError on nans.\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001251"\n"
1252">>> (10.0).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001253"(10, 1)\n"
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001254">>> (0.0).as_integer_ratio()\n"
1255"(0, 1)\n"
1256">>> (-.25).as_integer_ratio()\n"
Raymond Hettinger04c96d52008-02-01 21:30:23 +00001257"(-1, 4)");
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001258
Guido van Rossum1899c2e1992-09-12 11:09:23 +00001259
Jeremy Hylton938ace62002-07-17 16:30:39 +00001260static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00001261float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
1262
Tim Peters6d6c1a32001-08-02 04:15:00 +00001263static PyObject *
1264float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1265{
1266 PyObject *x = Py_False; /* Integer zero */
Martin v. Löwis15e62742006-02-27 16:46:16 +00001267 static char *kwlist[] = {"x", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00001268
Guido van Rossumbef14172001-08-29 15:47:46 +00001269 if (type != &PyFloat_Type)
1270 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001271 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
1272 return NULL;
1273 if (PyString_Check(x))
1274 return PyFloat_FromString(x, NULL);
1275 return PyNumber_Float(x);
1276}
1277
Guido van Rossumbef14172001-08-29 15:47:46 +00001278/* Wimpy, slow approach to tp_new calls for subtypes of float:
1279 first create a regular float from whatever arguments we got,
1280 then allocate a subtype instance and initialize its ob_fval
1281 from the regular float. The regular float is then thrown away.
1282*/
1283static PyObject *
1284float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1285{
Anthony Baxter377be112006-04-11 06:54:30 +00001286 PyObject *tmp, *newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001287
1288 assert(PyType_IsSubtype(type, &PyFloat_Type));
1289 tmp = float_new(&PyFloat_Type, args, kwds);
1290 if (tmp == NULL)
1291 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +00001292 assert(PyFloat_CheckExact(tmp));
Anthony Baxter377be112006-04-11 06:54:30 +00001293 newobj = type->tp_alloc(type, 0);
1294 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00001295 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00001296 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00001297 }
Anthony Baxter377be112006-04-11 06:54:30 +00001298 ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
Guido van Rossumbef14172001-08-29 15:47:46 +00001299 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00001300 return newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00001301}
1302
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001303static PyObject *
1304float_getnewargs(PyFloatObject *v)
1305{
1306 return Py_BuildValue("(d)", v->ob_fval);
1307}
1308
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001309/* this is for the benefit of the pack/unpack routines below */
1310
1311typedef enum {
1312 unknown_format, ieee_big_endian_format, ieee_little_endian_format
1313} float_format_type;
1314
1315static float_format_type double_format, float_format;
1316static float_format_type detected_double_format, detected_float_format;
1317
1318static PyObject *
1319float_getformat(PyTypeObject *v, PyObject* arg)
1320{
1321 char* s;
1322 float_format_type r;
1323
1324 if (!PyString_Check(arg)) {
1325 PyErr_Format(PyExc_TypeError,
1326 "__getformat__() argument must be string, not %.500s",
Christian Heimese93237d2007-12-19 02:37:44 +00001327 Py_TYPE(arg)->tp_name);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001328 return NULL;
1329 }
1330 s = PyString_AS_STRING(arg);
1331 if (strcmp(s, "double") == 0) {
1332 r = double_format;
1333 }
1334 else if (strcmp(s, "float") == 0) {
1335 r = float_format;
1336 }
1337 else {
1338 PyErr_SetString(PyExc_ValueError,
1339 "__getformat__() argument 1 must be "
1340 "'double' or 'float'");
1341 return NULL;
1342 }
1343
1344 switch (r) {
1345 case unknown_format:
1346 return PyString_FromString("unknown");
1347 case ieee_little_endian_format:
1348 return PyString_FromString("IEEE, little-endian");
1349 case ieee_big_endian_format:
1350 return PyString_FromString("IEEE, big-endian");
1351 default:
1352 Py_FatalError("insane float_format or double_format");
1353 return NULL;
1354 }
1355}
1356
1357PyDoc_STRVAR(float_getformat_doc,
1358"float.__getformat__(typestr) -> string\n"
1359"\n"
1360"You probably don't want to use this function. It exists mainly to be\n"
1361"used in Python's test suite.\n"
1362"\n"
1363"typestr must be 'double' or 'float'. This function returns whichever of\n"
1364"'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"
1365"format of floating point numbers used by the C type named by typestr.");
1366
1367static PyObject *
1368float_setformat(PyTypeObject *v, PyObject* args)
1369{
1370 char* typestr;
1371 char* format;
1372 float_format_type f;
1373 float_format_type detected;
1374 float_format_type *p;
1375
1376 if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
1377 return NULL;
1378
1379 if (strcmp(typestr, "double") == 0) {
1380 p = &double_format;
1381 detected = detected_double_format;
1382 }
1383 else if (strcmp(typestr, "float") == 0) {
1384 p = &float_format;
1385 detected = detected_float_format;
1386 }
1387 else {
1388 PyErr_SetString(PyExc_ValueError,
1389 "__setformat__() argument 1 must "
1390 "be 'double' or 'float'");
1391 return NULL;
1392 }
1393
1394 if (strcmp(format, "unknown") == 0) {
1395 f = unknown_format;
1396 }
1397 else if (strcmp(format, "IEEE, little-endian") == 0) {
1398 f = ieee_little_endian_format;
1399 }
1400 else if (strcmp(format, "IEEE, big-endian") == 0) {
1401 f = ieee_big_endian_format;
1402 }
1403 else {
1404 PyErr_SetString(PyExc_ValueError,
1405 "__setformat__() argument 2 must be "
1406 "'unknown', 'IEEE, little-endian' or "
1407 "'IEEE, big-endian'");
1408 return NULL;
1409
1410 }
1411
1412 if (f != unknown_format && f != detected) {
1413 PyErr_Format(PyExc_ValueError,
1414 "can only set %s format to 'unknown' or the "
1415 "detected platform value", typestr);
1416 return NULL;
1417 }
1418
1419 *p = f;
1420 Py_RETURN_NONE;
1421}
1422
1423PyDoc_STRVAR(float_setformat_doc,
1424"float.__setformat__(typestr, fmt) -> None\n"
1425"\n"
1426"You probably don't want to use this function. It exists mainly to be\n"
1427"used in Python's test suite.\n"
1428"\n"
1429"typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"
1430"'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"
1431"one of the latter two if it appears to match the underlying C reality.\n"
1432"\n"
1433"Overrides the automatic determination of C-level floating point type.\n"
1434"This affects how floats are converted to and from binary strings.");
1435
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001436static PyObject *
1437float_getzero(PyObject *v, void *closure)
1438{
1439 return PyFloat_FromDouble(0.0);
1440}
1441
Eric Smitha9f7d622008-02-17 19:46:49 +00001442static PyObject *
1443float__format__(PyObject *self, PyObject *args)
1444{
1445 PyObject *format_spec;
1446
1447 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
1448 return NULL;
1449 if (PyString_Check(format_spec))
1450 return string_float__format__(self, args);
1451 if (PyUnicode_Check(format_spec)) {
1452 /* Convert format_spec to a str */
1453 PyObject *result = NULL;
1454 PyObject *newargs = NULL;
1455 PyObject *string_format_spec = NULL;
1456
1457 string_format_spec = PyObject_Str(format_spec);
1458 if (string_format_spec == NULL)
1459 goto done;
1460
1461 newargs = Py_BuildValue("(O)", string_format_spec);
1462 if (newargs == NULL)
1463 goto done;
1464
1465 result = string_float__format__(self, newargs);
1466
1467 done:
1468 Py_XDECREF(string_format_spec);
1469 Py_XDECREF(newargs);
1470 return result;
1471 }
1472 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
1473 return NULL;
1474}
1475
1476PyDoc_STRVAR(float__format__doc,
1477"float.__format__(format_spec) -> string\n"
1478"\n"
1479"Formats the float according to format_spec.");
1480
1481
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001482static PyMethodDef float_methods[] = {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001483 {"conjugate", (PyCFunction)float_float, METH_NOARGS,
1484 "Returns self, the complex conjugate of any float."},
1485 {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
1486 "Returns the Integral closest to x between 0 and x."},
Jeffrey Yasskin3ea7b412008-01-27 23:08:46 +00001487 {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
1488 float_as_integer_ratio_doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001489 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001490 {"__getformat__", (PyCFunction)float_getformat,
1491 METH_O|METH_CLASS, float_getformat_doc},
1492 {"__setformat__", (PyCFunction)float_setformat,
1493 METH_VARARGS|METH_CLASS, float_setformat_doc},
Eric Smitha9f7d622008-02-17 19:46:49 +00001494 {"__format__", (PyCFunction)float__format__,
1495 METH_VARARGS, float__format__doc},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001496 {NULL, NULL} /* sentinel */
1497};
1498
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001499static PyGetSetDef float_getset[] = {
1500 {"real",
1501 (getter)float_float, (setter)NULL,
1502 "the real part of a complex number",
1503 NULL},
1504 {"imag",
1505 (getter)float_getzero, (setter)NULL,
1506 "the imaginary part of a complex number",
1507 NULL},
1508 {NULL} /* Sentinel */
1509};
1510
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001511PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001512"float(x) -> floating point number\n\
1513\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001514Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001515
1516
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001517static PyNumberMethods float_as_number = {
Georg Brandl347b3002006-03-30 11:57:00 +00001518 float_add, /*nb_add*/
1519 float_sub, /*nb_subtract*/
1520 float_mul, /*nb_multiply*/
1521 float_classic_div, /*nb_divide*/
1522 float_rem, /*nb_remainder*/
1523 float_divmod, /*nb_divmod*/
1524 float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001525 (unaryfunc)float_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001526 (unaryfunc)float_float, /*nb_positive*/
Guido van Rossumb6775db1994-08-01 11:34:53 +00001527 (unaryfunc)float_abs, /*nb_absolute*/
1528 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +00001529 0, /*nb_invert*/
1530 0, /*nb_lshift*/
1531 0, /*nb_rshift*/
1532 0, /*nb_and*/
1533 0, /*nb_xor*/
1534 0, /*nb_or*/
Georg Brandl347b3002006-03-30 11:57:00 +00001535 float_coerce, /*nb_coerce*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001536 float_trunc, /*nb_int*/
1537 float_trunc, /*nb_long*/
Georg Brandl347b3002006-03-30 11:57:00 +00001538 float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00001539 0, /* nb_oct */
1540 0, /* nb_hex */
1541 0, /* nb_inplace_add */
1542 0, /* nb_inplace_subtract */
1543 0, /* nb_inplace_multiply */
1544 0, /* nb_inplace_divide */
1545 0, /* nb_inplace_remainder */
1546 0, /* nb_inplace_power */
1547 0, /* nb_inplace_lshift */
1548 0, /* nb_inplace_rshift */
1549 0, /* nb_inplace_and */
1550 0, /* nb_inplace_xor */
1551 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +00001552 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00001553 float_div, /* nb_true_divide */
1554 0, /* nb_inplace_floor_divide */
1555 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001556};
1557
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001558PyTypeObject PyFloat_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001559 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001560 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001561 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001562 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00001563 (destructor)float_dealloc, /* tp_dealloc */
1564 (printfunc)float_print, /* tp_print */
1565 0, /* tp_getattr */
1566 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +00001567 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001568 (reprfunc)float_repr, /* tp_repr */
1569 &float_as_number, /* tp_as_number */
1570 0, /* tp_as_sequence */
1571 0, /* tp_as_mapping */
1572 (hashfunc)float_hash, /* tp_hash */
1573 0, /* tp_call */
1574 (reprfunc)float_str, /* tp_str */
1575 PyObject_GenericGetAttr, /* tp_getattro */
1576 0, /* tp_setattro */
1577 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00001578 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
1579 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001580 float_doc, /* tp_doc */
1581 0, /* tp_traverse */
1582 0, /* tp_clear */
Georg Brandl347b3002006-03-30 11:57:00 +00001583 float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001584 0, /* tp_weaklistoffset */
1585 0, /* tp_iter */
1586 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00001587 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001588 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001589 float_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00001590 0, /* tp_base */
1591 0, /* tp_dict */
1592 0, /* tp_descr_get */
1593 0, /* tp_descr_set */
1594 0, /* tp_dictoffset */
1595 0, /* tp_init */
1596 0, /* tp_alloc */
1597 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001598};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001599
1600void
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001601_PyFloat_Init(void)
1602{
1603 /* We attempt to determine if this machine is using IEEE
1604 floating point formats by peering at the bits of some
1605 carefully chosen values. If it looks like we are on an
1606 IEEE platform, the float packing/unpacking routines can
1607 just copy bits, if not they resort to arithmetic & shifts
1608 and masks. The shifts & masks approach works on all finite
1609 values, but what happens to infinities, NaNs and signed
1610 zeroes on packing is an accident, and attempting to unpack
1611 a NaN or an infinity will raise an exception.
1612
1613 Note that if we're on some whacked-out platform which uses
1614 IEEE formats but isn't strictly little-endian or big-
1615 endian, we will fall back to the portable shifts & masks
1616 method. */
1617
1618#if SIZEOF_DOUBLE == 8
1619 {
1620 double x = 9006104071832581.0;
1621 if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
1622 detected_double_format = ieee_big_endian_format;
1623 else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
1624 detected_double_format = ieee_little_endian_format;
1625 else
1626 detected_double_format = unknown_format;
1627 }
1628#else
1629 detected_double_format = unknown_format;
1630#endif
1631
1632#if SIZEOF_FLOAT == 4
1633 {
1634 float y = 16711938.0;
1635 if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
1636 detected_float_format = ieee_big_endian_format;
1637 else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
1638 detected_float_format = ieee_little_endian_format;
1639 else
1640 detected_float_format = unknown_format;
1641 }
1642#else
1643 detected_float_format = unknown_format;
1644#endif
1645
1646 double_format = detected_double_format;
1647 float_format = detected_float_format;
Christian Heimesf15c66e2007-12-11 00:54:34 +00001648
1649#ifdef Py_BROKEN_REPR
Christian Heimes284d9272007-12-10 22:28:56 +00001650 /* Initialize floating point repr */
1651 _PyFloat_DigitsInit();
Christian Heimesf15c66e2007-12-11 00:54:34 +00001652#endif
Christian Heimes796fc312008-01-30 18:58:29 +00001653 /* Init float info */
1654 if (FloatInfoType.tp_name == 0)
1655 PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001656}
1657
1658void
Christian Heimes422051a2008-02-04 18:00:12 +00001659PyFloat_CompactFreeList(size_t *pbc, size_t *pbf, size_t *bsum)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +00001660{
Guido van Rossum3fce8831999-03-12 19:43:17 +00001661 PyFloatObject *p;
1662 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +00001663 unsigned i;
Christian Heimes422051a2008-02-04 18:00:12 +00001664 size_t bc = 0, bf = 0; /* block count, number of freed blocks */
1665 size_t fsum = 0; /* total unfreed ints */
1666 int frem; /* remaining unfreed ints per block */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001667
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001668 list = block_list;
1669 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001670 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001671 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001672 bc++;
1673 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001674 for (i = 0, p = &list->objects[0];
1675 i < N_FLOATOBJECTS;
1676 i++, p++) {
Christian Heimese93237d2007-12-19 02:37:44 +00001677 if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001678 frem++;
1679 }
Guido van Rossum3fce8831999-03-12 19:43:17 +00001680 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001681 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +00001682 list->next = block_list;
1683 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001684 for (i = 0, p = &list->objects[0];
1685 i < N_FLOATOBJECTS;
1686 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +00001687 if (!PyFloat_CheckExact(p) ||
Christian Heimese93237d2007-12-19 02:37:44 +00001688 Py_REFCNT(p) == 0) {
1689 Py_TYPE(p) = (struct _typeobject *)
Guido van Rossumd7b5fb81999-03-19 20:59:40 +00001690 free_list;
1691 free_list = p;
1692 }
1693 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001694 }
1695 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +00001696 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001697 bf++;
1698 }
1699 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +00001700 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +00001701 }
Christian Heimes422051a2008-02-04 18:00:12 +00001702 *pbc = bc;
1703 *pbf = bf;
1704 *bsum = fsum;
1705}
1706
1707void
1708PyFloat_Fini(void)
1709{
1710 PyFloatObject *p;
1711 PyFloatBlock *list;
1712 unsigned i;
1713 size_t bc, bf; /* block count, number of freed blocks */
1714 size_t fsum; /* total unfreed floats per block */
1715
1716 PyFloat_CompactFreeList(&bc, &bf, &fsum);
1717
Guido van Rossum3fce8831999-03-12 19:43:17 +00001718 if (!Py_VerboseFlag)
1719 return;
1720 fprintf(stderr, "# cleanup floats");
1721 if (!fsum) {
1722 fprintf(stderr, "\n");
1723 }
1724 else {
1725 fprintf(stderr,
Neal Norwitzc0a56ff2008-03-27 06:52:01 +00001726 ": %" PY_FORMAT_SIZE_T "d unfreed float%s in %"
Christian Heimes422051a2008-02-04 18:00:12 +00001727 PY_FORMAT_SIZE_T "d out of %"
1728 PY_FORMAT_SIZE_T "d block%s\n",
Guido van Rossum3fce8831999-03-12 19:43:17 +00001729 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.
Tim Peters9905b942003-03-20 20:53:32 +00001758 */
1759int
1760_PyFloat_Pack4(double x, unsigned char *p, int le)
1761{
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001762 if (float_format == unknown_format) {
1763 unsigned char sign;
1764 int e;
1765 double f;
1766 unsigned int fbits;
1767 int incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001768
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001769 if (le) {
1770 p += 3;
1771 incr = -1;
1772 }
Tim Peters9905b942003-03-20 20:53:32 +00001773
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001774 if (x < 0) {
1775 sign = 1;
1776 x = -x;
1777 }
1778 else
1779 sign = 0;
Tim Peters9905b942003-03-20 20:53:32 +00001780
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001781 f = frexp(x, &e);
Tim Peters9905b942003-03-20 20:53:32 +00001782
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001783 /* Normalize f to be in the range [1.0, 2.0) */
1784 if (0.5 <= f && f < 1.0) {
1785 f *= 2.0;
1786 e--;
1787 }
1788 else if (f == 0.0)
1789 e = 0;
1790 else {
1791 PyErr_SetString(PyExc_SystemError,
1792 "frexp() result out of range");
1793 return -1;
1794 }
1795
1796 if (e >= 128)
1797 goto Overflow;
1798 else if (e < -126) {
1799 /* Gradual underflow */
1800 f = ldexp(f, 126 + e);
1801 e = 0;
1802 }
1803 else if (!(e == 0 && f == 0.0)) {
1804 e += 127;
1805 f -= 1.0; /* Get rid of leading 1 */
1806 }
1807
1808 f *= 8388608.0; /* 2**23 */
1809 fbits = (unsigned int)(f + 0.5); /* Round */
1810 assert(fbits <= 8388608);
1811 if (fbits >> 23) {
1812 /* The carry propagated out of a string of 23 1 bits. */
1813 fbits = 0;
1814 ++e;
1815 if (e >= 255)
1816 goto Overflow;
1817 }
1818
1819 /* First byte */
1820 *p = (sign << 7) | (e >> 1);
1821 p += incr;
1822
1823 /* Second byte */
1824 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1825 p += incr;
1826
1827 /* Third byte */
1828 *p = (fbits >> 8) & 0xFF;
1829 p += incr;
1830
1831 /* Fourth byte */
1832 *p = fbits & 0xFF;
1833
1834 /* Done */
1835 return 0;
1836
Tim Peters9905b942003-03-20 20:53:32 +00001837 }
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001838 else {
Michael W. Hudson3095ad02005-06-30 00:02:26 +00001839 float y = (float)x;
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001840 const char *s = (char*)&y;
1841 int i, incr = 1;
Tim Peters9905b942003-03-20 20:53:32 +00001842
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00001843 if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
1844 goto Overflow;
1845
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001846 if ((float_format == ieee_little_endian_format && !le)
1847 || (float_format == ieee_big_endian_format && le)) {
1848 p += 3;
1849 incr = -1;
1850 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00001851
Michael W. Hudsonba283e22005-05-27 15:23:20 +00001852 for (i = 0; i < 4; i++) {
1853 *p = *s++;
1854 p += incr;
1855 }
1856 return 0;
Tim Peters9905b942003-03-20 20:53:32 +00001857 }
Mark Dickinsonc23b8a72008-03-14 14:23:37 +00001858 Overflow:
1859 PyErr_SetString(PyExc_OverflowError,
1860 "float too large to pack with f format");
1861 return -1;
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}