blob: 774d2ead6a423bb8c05ac24d2363a2ab4c2fd83c [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Float object implementation */
3
Guido van Rossum2a9096b1990-10-21 22:15:08 +00004/* XXX There should be overflow checks here, but it's hard to check
5 for any kind of float exception without losing portability. */
6
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008
Guido van Rossum3f5da241990-12-20 15:06:42 +00009#include <ctype.h>
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Jack Janseneddc1442003-11-20 01:44:59 +000011#if !defined(__STDC__)
Tim Petersdbd9ba62000-07-09 03:09:57 +000012extern double fmod(double, double);
13extern double pow(double, double);
Guido van Rossum6923e131990-11-02 17:50:43 +000014#endif
15
Guido van Rossum93ad0df1997-05-13 21:00:42 +000016/* Special free list -- see comments for same code in intobject.c. */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000017#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
Guido van Rossum3fce8831999-03-12 19:43:17 +000018#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
Guido van Rossumf61bbc81999-03-12 00:12:21 +000019#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
Guido van Rossum3fce8831999-03-12 19:43:17 +000020
Guido van Rossum3fce8831999-03-12 19:43:17 +000021struct _floatblock {
22 struct _floatblock *next;
23 PyFloatObject objects[N_FLOATOBJECTS];
24};
25
26typedef struct _floatblock PyFloatBlock;
27
28static PyFloatBlock *block_list = NULL;
29static PyFloatObject *free_list = NULL;
30
Guido van Rossum93ad0df1997-05-13 21:00:42 +000031static PyFloatObject *
Fred Drakefd99de62000-07-09 05:02:18 +000032fill_free_list(void)
Guido van Rossum93ad0df1997-05-13 21:00:42 +000033{
34 PyFloatObject *p, *q;
Guido van Rossumb18618d2000-05-03 23:44:39 +000035 /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
36 p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
Guido van Rossum93ad0df1997-05-13 21:00:42 +000037 if (p == NULL)
Guido van Rossumb18618d2000-05-03 23:44:39 +000038 return (PyFloatObject *) PyErr_NoMemory();
Guido van Rossum3fce8831999-03-12 19:43:17 +000039 ((PyFloatBlock *)p)->next = block_list;
40 block_list = (PyFloatBlock *)p;
41 p = &((PyFloatBlock *)p)->objects[0];
Guido van Rossum93ad0df1997-05-13 21:00:42 +000042 q = p + N_FLOATOBJECTS;
43 while (--q > p)
Guido van Rossumf61bbc81999-03-12 00:12:21 +000044 q->ob_type = (struct _typeobject *)(q-1);
45 q->ob_type = NULL;
Guido van Rossum93ad0df1997-05-13 21:00:42 +000046 return p + N_FLOATOBJECTS - 1;
47}
48
Guido van Rossumc0b618a1997-05-02 03:12:38 +000049PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +000050PyFloat_FromDouble(double fval)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000051{
Guido van Rossum93ad0df1997-05-13 21:00:42 +000052 register PyFloatObject *op;
53 if (free_list == NULL) {
54 if ((free_list = fill_free_list()) == NULL)
55 return NULL;
56 }
Guido van Rossume3a8e7e2002-08-19 19:26:42 +000057 /* Inline PyObject_New */
Guido van Rossum93ad0df1997-05-13 21:00:42 +000058 op = free_list;
Guido van Rossumf61bbc81999-03-12 00:12:21 +000059 free_list = (PyFloatObject *)op->ob_type;
Guido van Rossumb18618d2000-05-03 23:44:39 +000060 PyObject_INIT(op, &PyFloat_Type);
Guido van Rossum2a9096b1990-10-21 22:15:08 +000061 op->ob_fval = fval;
Guido van Rossumc0b618a1997-05-02 03:12:38 +000062 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000063}
64
Tim Petersef14d732000-09-23 03:39:17 +000065/**************************************************************************
66RED_FLAG 22-Sep-2000 tim
67PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,
68
691. If v was a regular string, *pend was set to point to its terminating
70 null byte. That's useless (the caller can find that without any
71 help from this function!).
72
732. If v was a Unicode string, or an object convertible to a character
74 buffer, *pend was set to point into stack trash (the auto temp
75 vector holding the character buffer). That was downright dangerous.
76
77Since we can't change the interface of a public API function, pend is
78still supported but now *officially* useless: if pend is not NULL,
79*pend is set to NULL.
80**************************************************************************/
Barry Warsaw226ae6c1999-10-12 19:54:53 +000081PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +000082PyFloat_FromString(PyObject *v, char **pend)
Barry Warsaw226ae6c1999-10-12 19:54:53 +000083{
Guido van Rossum4c08d552000-03-10 22:55:18 +000084 const char *s, *last, *end;
Barry Warsaw226ae6c1999-10-12 19:54:53 +000085 double x;
Tim Petersef14d732000-09-23 03:39:17 +000086 char buffer[256]; /* for errors */
Martin v. Löwis339d0f72001-08-17 18:39:25 +000087#ifdef Py_USING_UNICODE
Tim Petersef14d732000-09-23 03:39:17 +000088 char s_buffer[256]; /* for objects convertible to a char buffer */
Martin v. Löwis339d0f72001-08-17 18:39:25 +000089#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +000090 int len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +000091
Tim Petersef14d732000-09-23 03:39:17 +000092 if (pend)
93 *pend = NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +000094 if (PyString_Check(v)) {
95 s = PyString_AS_STRING(v);
96 len = PyString_GET_SIZE(v);
97 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +000098#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +000099 else if (PyUnicode_Check(v)) {
Guido van Rossum9e896b32000-04-05 20:11:21 +0000100 if (PyUnicode_GET_SIZE(v) >= sizeof(s_buffer)) {
101 PyErr_SetString(PyExc_ValueError,
Tim Petersef14d732000-09-23 03:39:17 +0000102 "Unicode float() literal too long to convert");
Guido van Rossum9e896b32000-04-05 20:11:21 +0000103 return NULL;
104 }
Tim Petersef14d732000-09-23 03:39:17 +0000105 if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
Guido van Rossum9e896b32000-04-05 20:11:21 +0000106 PyUnicode_GET_SIZE(v),
Tim Petersd2364e82001-11-01 20:09:42 +0000107 s_buffer,
Guido van Rossum9e896b32000-04-05 20:11:21 +0000108 NULL))
109 return NULL;
110 s = s_buffer;
Trent Micka248fb62000-08-12 21:37:39 +0000111 len = (int)strlen(s);
Guido van Rossum9e896b32000-04-05 20:11:21 +0000112 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000113#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +0000114 else if (PyObject_AsCharBuffer(v, &s, &len)) {
115 PyErr_SetString(PyExc_TypeError,
Skip Montanaro71390a92002-05-02 13:03:22 +0000116 "float() argument must be a string or a number");
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000117 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000118 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000119
Guido van Rossum4c08d552000-03-10 22:55:18 +0000120 last = s + len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000121 while (*s && isspace(Py_CHARMASK(*s)))
122 s++;
Tim Petersef14d732000-09-23 03:39:17 +0000123 if (*s == '\0') {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000124 PyErr_SetString(PyExc_ValueError, "empty string for float()");
125 return NULL;
126 }
Tim Petersef14d732000-09-23 03:39:17 +0000127 /* We don't care about overflow or underflow. If the platform supports
128 * them, infinities and signed zeroes (on underflow) are fine.
129 * However, strtod can return 0 for denormalized numbers, where atof
130 * does not. So (alas!) we special-case a zero result. Note that
131 * whether strtod sets errno on underflow is not defined, so we can't
132 * key off errno.
133 */
Tim Peters858346e2000-09-25 21:01:28 +0000134 PyFPE_START_PROTECT("strtod", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000135 x = PyOS_ascii_strtod(s, (char **)&end);
Tim Peters858346e2000-09-25 21:01:28 +0000136 PyFPE_END_PROTECT(x)
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000137 errno = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000138 /* Believe it or not, Solaris 2.6 can move end *beyond* the null
Tim Petersef14d732000-09-23 03:39:17 +0000139 byte at the end of the string, when the input is inf(inity). */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000140 if (end > last)
141 end = last;
Tim Petersef14d732000-09-23 03:39:17 +0000142 if (end == s) {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000143 PyOS_snprintf(buffer, sizeof(buffer),
144 "invalid literal for float(): %.200s", s);
Tim Petersef14d732000-09-23 03:39:17 +0000145 PyErr_SetString(PyExc_ValueError, buffer);
146 return NULL;
147 }
148 /* Since end != s, the platform made *some* kind of sense out
149 of the input. Trust it. */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000150 while (*end && isspace(Py_CHARMASK(*end)))
151 end++;
152 if (*end != '\0') {
Barry Warsawaf8aef92001-11-28 20:52:21 +0000153 PyOS_snprintf(buffer, sizeof(buffer),
154 "invalid literal for float(): %.200s", s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000155 PyErr_SetString(PyExc_ValueError, buffer);
156 return NULL;
157 }
Guido van Rossum4c08d552000-03-10 22:55:18 +0000158 else if (end != last) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000159 PyErr_SetString(PyExc_ValueError,
160 "null byte in argument for float()");
161 return NULL;
162 }
Tim Petersef14d732000-09-23 03:39:17 +0000163 if (x == 0.0) {
164 /* See above -- may have been strtod being anal
165 about denorms. */
Tim Peters858346e2000-09-25 21:01:28 +0000166 PyFPE_START_PROTECT("atof", return NULL)
Martin v. Löwis737ea822004-06-08 18:52:54 +0000167 x = PyOS_ascii_atof(s);
Tim Peters858346e2000-09-25 21:01:28 +0000168 PyFPE_END_PROTECT(x)
Tim Petersef14d732000-09-23 03:39:17 +0000169 errno = 0; /* whether atof ever set errno is undefined */
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000170 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +0000171 return PyFloat_FromDouble(x);
172}
173
Guido van Rossum234f9421993-06-17 12:35:49 +0000174static void
Fred Drakefd99de62000-07-09 05:02:18 +0000175float_dealloc(PyFloatObject *op)
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000176{
Guido van Rossum9475a232001-10-05 20:51:39 +0000177 if (PyFloat_CheckExact(op)) {
178 op->ob_type = (struct _typeobject *)free_list;
179 free_list = op;
180 }
181 else
182 op->ob_type->tp_free((PyObject *)op);
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000183}
184
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000185double
Fred Drakefd99de62000-07-09 05:02:18 +0000186PyFloat_AsDouble(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000187{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000188 PyNumberMethods *nb;
189 PyFloatObject *fo;
Guido van Rossumb6775db1994-08-01 11:34:53 +0000190 double val;
Tim Petersd2364e82001-11-01 20:09:42 +0000191
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000192 if (op && PyFloat_Check(op))
193 return PyFloat_AS_DOUBLE((PyFloatObject*) op);
Tim Petersd2364e82001-11-01 20:09:42 +0000194
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000195 if (op == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000196 PyErr_BadArgument();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000197 return -1;
198 }
Tim Petersd2364e82001-11-01 20:09:42 +0000199
Neil Schemenauer2c77e902002-11-18 16:06:21 +0000200 if ((nb = op->ob_type->tp_as_number) == NULL || nb->nb_float == NULL) {
201 PyErr_SetString(PyExc_TypeError, "a float is required");
202 return -1;
203 }
204
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000205 fo = (PyFloatObject*) (*nb->nb_float) (op);
Guido van Rossumb6775db1994-08-01 11:34:53 +0000206 if (fo == NULL)
207 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000208 if (!PyFloat_Check(fo)) {
209 PyErr_SetString(PyExc_TypeError,
210 "nb_float should return float object");
Guido van Rossumb6775db1994-08-01 11:34:53 +0000211 return -1;
212 }
Tim Petersd2364e82001-11-01 20:09:42 +0000213
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000214 val = PyFloat_AS_DOUBLE(fo);
215 Py_DECREF(fo);
Tim Petersd2364e82001-11-01 20:09:42 +0000216
Guido van Rossumb6775db1994-08-01 11:34:53 +0000217 return val;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218}
219
220/* Methods */
221
Tim Peters97019e42001-11-28 22:43:45 +0000222static void
223format_float(char *buf, size_t buflen, PyFloatObject *v, int precision)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000224{
225 register char *cp;
Martin v. Löwis737ea822004-06-08 18:52:54 +0000226 char format[32];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000227 /* Subroutine for float_repr and float_print.
228 We want float numbers to be recognizable as such,
229 i.e., they should contain a decimal point or an exponent.
230 However, %g may print the number as an integer;
231 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000232
233 assert(PyFloat_Check(v));
Martin v. Löwis737ea822004-06-08 18:52:54 +0000234 PyOS_snprintf(format, 32, "%%.%ig", precision);
235 PyOS_ascii_formatd(buf, buflen, format, v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000236 cp = buf;
237 if (*cp == '-')
238 cp++;
239 for (; *cp != '\0'; cp++) {
240 /* Any non-digit means it's not an integer;
241 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000242 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000243 break;
244 }
245 if (*cp == '\0') {
246 *cp++ = '.';
247 *cp++ = '0';
248 *cp++ = '\0';
249 }
250}
251
Tim Peters97019e42001-11-28 22:43:45 +0000252/* XXX PyFloat_AsStringEx should not be a public API function (for one
253 XXX thing, its signature passes a buffer without a length; for another,
254 XXX it isn't useful outside this file).
255*/
256void
257PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
258{
259 format_float(buf, 100, v, precision);
260}
261
Neil Schemenauer32117e52001-01-04 01:44:34 +0000262/* Macro and helper that convert PyObject obj to a C double and store
263 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000264 slot function. If conversion to double raises an exception, obj is
265 set to NULL, and the function invoking this macro returns NULL. If
266 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
267 stored in obj, and returned from the function invoking this macro.
268*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000269#define CONVERT_TO_DOUBLE(obj, dbl) \
270 if (PyFloat_Check(obj)) \
271 dbl = PyFloat_AS_DOUBLE(obj); \
272 else if (convert_to_double(&(obj), &(dbl)) < 0) \
273 return obj;
274
275static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000276convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000277{
278 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000279
Neil Schemenauer32117e52001-01-04 01:44:34 +0000280 if (PyInt_Check(obj)) {
281 *dbl = (double)PyInt_AS_LONG(obj);
282 }
283 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000284 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000285 if (*dbl == -1.0 && PyErr_Occurred()) {
286 *v = NULL;
287 return -1;
288 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000289 }
290 else {
291 Py_INCREF(Py_NotImplemented);
292 *v = Py_NotImplemented;
293 return -1;
294 }
295 return 0;
296}
297
Guido van Rossum57072eb1999-12-23 19:00:28 +0000298/* Precisions used by repr() and str(), respectively.
299
300 The repr() precision (17 significant decimal digits) is the minimal number
301 that is guaranteed to have enough precision so that if the number is read
302 back in the exact same binary value is recreated. This is true for IEEE
303 floating point by design, and also happens to work for all other modern
304 hardware.
305
306 The str() precision is chosen so that in most cases, the rounding noise
307 created by various operations is suppressed, while giving plenty of
308 precision for practical use.
309
310*/
311
312#define PREC_REPR 17
313#define PREC_STR 12
314
Tim Peters97019e42001-11-28 22:43:45 +0000315/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
316 XXX they pass a char buffer without passing a length.
317*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000318void
Fred Drakefd99de62000-07-09 05:02:18 +0000319PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000320{
Tim Peters97019e42001-11-28 22:43:45 +0000321 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000322}
323
Tim Peters72f98e92001-05-08 15:19:57 +0000324void
325PyFloat_AsReprString(char *buf, PyFloatObject *v)
326{
Tim Peters97019e42001-11-28 22:43:45 +0000327 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000328}
329
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000330/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000331static int
Fred Drakefd99de62000-07-09 05:02:18 +0000332float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000333{
334 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000335 format_float(buf, sizeof(buf), v,
336 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000337 fputs(buf, fp);
Guido van Rossum90933611991-06-07 16:10:43 +0000338 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000339}
340
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000342float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000343{
344 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000345 format_float(buf, sizeof(buf), v, PREC_REPR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000346 return PyString_FromString(buf);
347}
348
349static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000350float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000351{
352 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000353 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000354 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000355}
356
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000357static PyObject*
358float_richcompare(PyObject *v, PyObject *w, int op)
359{
360 double i, j;
361 int r = 0;
362
363 CONVERT_TO_DOUBLE(v, i);
364 CONVERT_TO_DOUBLE(w, j);
365
366 PyFPE_START_PROTECT("richcompare", return NULL)
367 switch (op) {
368 case Py_EQ:
369 r = i==j;
370 break;
371 case Py_NE:
372 r = i!=j;
373 break;
374 case Py_LE:
375 r = i<=j;
376 break;
377 case Py_GE:
378 r = i>=j;
379 break;
380 case Py_LT:
381 r = i<j;
382 break;
383 case Py_GT:
384 r = i>j;
385 break;
386 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000387 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000388 return PyBool_FromLong(r);
389}
390
Guido van Rossum9bfef441993-03-29 10:43:31 +0000391static long
Fred Drakefd99de62000-07-09 05:02:18 +0000392float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000393{
Tim Peters39dce292000-08-15 03:34:48 +0000394 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000395}
396
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000398float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000399{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000400 double a,b;
401 CONVERT_TO_DOUBLE(v, a);
402 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000403 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000404 a = a + b;
405 PyFPE_END_PROTECT(a)
406 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407}
408
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000409static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000410float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000411{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000412 double a,b;
413 CONVERT_TO_DOUBLE(v, a);
414 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000415 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000416 a = a - b;
417 PyFPE_END_PROTECT(a)
418 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000419}
420
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000421static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000422float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000423{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000424 double a,b;
425 CONVERT_TO_DOUBLE(v, a);
426 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000427 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000428 a = a * b;
429 PyFPE_END_PROTECT(a)
430 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000431}
432
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000433static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000434float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000435{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000436 double a,b;
437 CONVERT_TO_DOUBLE(v, a);
438 CONVERT_TO_DOUBLE(w, b);
439 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000440 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000441 return NULL;
442 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000443 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000444 a = a / b;
445 PyFPE_END_PROTECT(a)
446 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000447}
448
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000449static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000450float_classic_div(PyObject *v, PyObject *w)
451{
452 double a,b;
453 CONVERT_TO_DOUBLE(v, a);
454 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000455 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000456 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
457 return NULL;
458 if (b == 0.0) {
459 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
460 return NULL;
461 }
462 PyFPE_START_PROTECT("divide", return 0)
463 a = a / b;
464 PyFPE_END_PROTECT(a)
465 return PyFloat_FromDouble(a);
466}
467
468static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000469float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000470{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000471 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000472 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000473 CONVERT_TO_DOUBLE(v, vx);
474 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000475 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000476 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000477 return NULL;
478 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000479 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000480 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000481 /* note: checking mod*wx < 0 is incorrect -- underflows to
482 0 if wx < sqrt(smallest nonzero double) */
483 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000484 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000485 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000486 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000487 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000488}
489
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000490static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000491float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000492{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000493 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000494 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000495 CONVERT_TO_DOUBLE(v, vx);
496 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000497 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000498 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000499 return NULL;
500 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000501 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000502 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000503 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000504 exact multiple of wx. But this is fp arithmetic, and fp
505 vx - mod is an approximation; the result is that div may
506 not be an exact integral value after the division, although
507 it will always be very close to one.
508 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000509 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000510 if (mod) {
511 /* ensure the remainder has the same sign as the denominator */
512 if ((wx < 0) != (mod < 0)) {
513 mod += wx;
514 div -= 1.0;
515 }
516 }
517 else {
518 /* the remainder is zero, and in the presence of signed zeroes
519 fmod returns different results across platforms; ensure
520 it has the same sign as the denominator; we'd like to do
521 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000522 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000523 if (wx < 0.0)
524 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000525 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000526 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000527 if (div) {
528 floordiv = floor(div);
529 if (div - floordiv > 0.5)
530 floordiv += 1.0;
531 }
532 else {
533 /* div is zero - get the same sign as the true quotient */
534 div *= div; /* hide "div = +0" from optimizers */
535 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
536 }
537 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000538 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000539}
540
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000541static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000542float_floor_div(PyObject *v, PyObject *w)
543{
544 PyObject *t, *r;
545
546 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000547 if (t == NULL || t == Py_NotImplemented)
548 return t;
549 assert(PyTuple_CheckExact(t));
550 r = PyTuple_GET_ITEM(t, 0);
551 Py_INCREF(r);
552 Py_DECREF(t);
553 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000554}
555
556static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000557float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000558{
559 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000560
561 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000562 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000563 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000564 return NULL;
565 }
566
Neil Schemenauer32117e52001-01-04 01:44:34 +0000567 CONVERT_TO_DOUBLE(v, iv);
568 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000569
570 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000571 if (iw == 0) { /* v**0 is 1, even 0**0 */
Tim Petersc54d1902000-10-06 00:36:09 +0000572 PyFPE_START_PROTECT("pow", return NULL)
573 if ((PyObject *)z != Py_None) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000574 double iz;
Neil Schemenauer010b0cc2001-01-08 06:29:50 +0000575 CONVERT_TO_DOUBLE(z, iz);
Tim Peters96685bf2001-08-23 22:31:37 +0000576 ix = fmod(1.0, iz);
577 if (ix != 0 && iz < 0)
578 ix += iz;
Guido van Rossum70d93461991-05-28 21:57:39 +0000579 }
Tim Petersc54d1902000-10-06 00:36:09 +0000580 else
581 ix = 1.0;
582 PyFPE_END_PROTECT(ix)
Tim Petersd2364e82001-11-01 20:09:42 +0000583 return PyFloat_FromDouble(ix);
Tim Petersc54d1902000-10-06 00:36:09 +0000584 }
Tim Peters96685bf2001-08-23 22:31:37 +0000585 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000586 if (iw < 0.0) {
587 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000588 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000589 return NULL;
590 }
591 return PyFloat_FromDouble(0.0);
592 }
Tim Peterse87568d2003-05-24 20:18:24 +0000593 if (iv < 0.0) {
594 /* Whether this is an error is a mess, and bumps into libm
595 * bugs so we have to figure it out ourselves.
596 */
597 if (iw != floor(iw)) {
598 PyErr_SetString(PyExc_ValueError, "negative number "
599 "cannot be raised to a fractional power");
600 return NULL;
601 }
602 /* iw is an exact integer, albeit perhaps a very large one.
603 * -1 raised to an exact integer should never be exceptional.
604 * Alas, some libms (chiefly glibc as of early 2003) return
605 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
606 * happen to be representable in a *C* integer. That's a
607 * bug; we let that slide in math.pow() (which currently
608 * reflects all platform accidents), but not for Python's **.
609 */
610 if (iv == -1.0 && !Py_IS_INFINITY(iw) && iw == iw) {
611 /* XXX the "iw == iw" was to weed out NaNs. This
612 * XXX doesn't actually work on all platforms.
613 */
614 /* Return 1 if iw is even, -1 if iw is odd; there's
615 * no guarantee that any C integral type is big
616 * enough to hold iw, so we have to check this
617 * indirectly.
618 */
619 ix = floor(iw * 0.5) * 2.0;
620 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
621 }
622 /* Else iv != -1.0, and overflow or underflow are possible.
623 * Unless we're to write pow() ourselves, we have to trust
624 * the platform to do this correctly.
625 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000626 }
Tim Peters96685bf2001-08-23 22:31:37 +0000627 errno = 0;
628 PyFPE_START_PROTECT("pow", return NULL)
629 ix = pow(iv, iw);
630 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000631 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000632 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000633 /* We don't expect any errno value other than ERANGE, but
634 * the range of libm bugs appears unbounded.
635 */
636 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
637 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000638 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000639 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000640 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000641}
642
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000643static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000644float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000645{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000646 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000647}
648
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000649static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000650float_pos(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000651{
Tim Peters0280cf72001-09-11 21:53:35 +0000652 if (PyFloat_CheckExact(v)) {
653 Py_INCREF(v);
654 return (PyObject *)v;
655 }
656 else
657 return PyFloat_FromDouble(v->ob_fval);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000658}
659
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000660static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000661float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000662{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000663 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000664}
665
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000666static int
Fred Drakefd99de62000-07-09 05:02:18 +0000667float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000668{
669 return v->ob_fval != 0.0;
670}
671
Guido van Rossum234f9421993-06-17 12:35:49 +0000672static int
Fred Drakefd99de62000-07-09 05:02:18 +0000673float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +0000674{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000675 if (PyInt_Check(*pw)) {
676 long x = PyInt_AsLong(*pw);
677 *pw = PyFloat_FromDouble((double)x);
678 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000679 return 0;
680 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000681 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +0000682 double x = PyLong_AsDouble(*pw);
683 if (x == -1.0 && PyErr_Occurred())
684 return -1;
685 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000686 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000687 return 0;
688 }
Guido van Rossum1952e382001-09-19 01:25:16 +0000689 else if (PyFloat_Check(*pw)) {
690 Py_INCREF(*pv);
691 Py_INCREF(*pw);
692 return 0;
693 }
Guido van Rossume6eefc21992-08-14 12:06:52 +0000694 return 1; /* Can't do it */
695}
696
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000697static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +0000698float_long(PyObject *v)
699{
700 double x = PyFloat_AsDouble(v);
701 return PyLong_FromDouble(x);
702}
703
704static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000705float_int(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000706{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000707 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000708 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000709
710 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000711 /* Try to get out cheap if this fits in a Python int. The attempt
712 * to cast to long must be protected, as C doesn't define what
713 * happens if the double is too big to fit in a long. Some rare
714 * systems raise an exception then (RISCOS was mentioned as one,
715 * and someone using a non-default option on Sun also bumped into
716 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
717 * still be vulnerable: if a long has more bits of precision than
718 * a double, casting MIN/MAX to double may yield an approximation,
719 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
720 * yield true from the C expression wholepart<=LONG_MAX, despite
721 * that wholepart is actually greater than LONG_MAX.
722 */
723 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
724 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000725 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000726 }
727 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000728}
729
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000730static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000731float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000732{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000733 Py_INCREF(v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000734 return v;
735}
736
737
Jeremy Hylton938ace62002-07-17 16:30:39 +0000738static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +0000739float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
740
Tim Peters6d6c1a32001-08-02 04:15:00 +0000741static PyObject *
742float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
743{
744 PyObject *x = Py_False; /* Integer zero */
745 static char *kwlist[] = {"x", 0};
746
Guido van Rossumbef14172001-08-29 15:47:46 +0000747 if (type != &PyFloat_Type)
748 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000749 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
750 return NULL;
751 if (PyString_Check(x))
752 return PyFloat_FromString(x, NULL);
753 return PyNumber_Float(x);
754}
755
Guido van Rossumbef14172001-08-29 15:47:46 +0000756/* Wimpy, slow approach to tp_new calls for subtypes of float:
757 first create a regular float from whatever arguments we got,
758 then allocate a subtype instance and initialize its ob_fval
759 from the regular float. The regular float is then thrown away.
760*/
761static PyObject *
762float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
763{
764 PyObject *tmp, *new;
765
766 assert(PyType_IsSubtype(type, &PyFloat_Type));
767 tmp = float_new(&PyFloat_Type, args, kwds);
768 if (tmp == NULL)
769 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +0000770 assert(PyFloat_CheckExact(tmp));
Guido van Rossumd93dce12001-08-30 03:09:31 +0000771 new = type->tp_alloc(type, 0);
Raymond Hettingerf4667932003-06-28 20:04:25 +0000772 if (new == NULL) {
773 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +0000774 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +0000775 }
Guido van Rossumbef14172001-08-29 15:47:46 +0000776 ((PyFloatObject *)new)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
777 Py_DECREF(tmp);
778 return new;
779}
780
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000781static PyObject *
782float_getnewargs(PyFloatObject *v)
783{
784 return Py_BuildValue("(d)", v->ob_fval);
785}
786
787static PyMethodDef float_methods[] = {
788 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
789 {NULL, NULL} /* sentinel */
790};
791
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000792PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000793"float(x) -> floating point number\n\
794\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000795Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000796
797
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000798static PyNumberMethods float_as_number = {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000799 (binaryfunc)float_add, /*nb_add*/
800 (binaryfunc)float_sub, /*nb_subtract*/
801 (binaryfunc)float_mul, /*nb_multiply*/
Guido van Rossum393661d2001-08-31 17:40:15 +0000802 (binaryfunc)float_classic_div, /*nb_divide*/
Guido van Rossumb6775db1994-08-01 11:34:53 +0000803 (binaryfunc)float_rem, /*nb_remainder*/
804 (binaryfunc)float_divmod, /*nb_divmod*/
Guido van Rossum0b7d02a1994-08-12 12:52:35 +0000805 (ternaryfunc)float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +0000806 (unaryfunc)float_neg, /*nb_negative*/
807 (unaryfunc)float_pos, /*nb_positive*/
808 (unaryfunc)float_abs, /*nb_absolute*/
809 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +0000810 0, /*nb_invert*/
811 0, /*nb_lshift*/
812 0, /*nb_rshift*/
813 0, /*nb_and*/
814 0, /*nb_xor*/
815 0, /*nb_or*/
Guido van Rossumb6775db1994-08-01 11:34:53 +0000816 (coercion)float_coerce, /*nb_coerce*/
817 (unaryfunc)float_int, /*nb_int*/
818 (unaryfunc)float_long, /*nb_long*/
819 (unaryfunc)float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +0000820 0, /* nb_oct */
821 0, /* nb_hex */
822 0, /* nb_inplace_add */
823 0, /* nb_inplace_subtract */
824 0, /* nb_inplace_multiply */
825 0, /* nb_inplace_divide */
826 0, /* nb_inplace_remainder */
827 0, /* nb_inplace_power */
828 0, /* nb_inplace_lshift */
829 0, /* nb_inplace_rshift */
830 0, /* nb_inplace_and */
831 0, /* nb_inplace_xor */
832 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +0000833 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +0000834 float_div, /* nb_true_divide */
835 0, /* nb_inplace_floor_divide */
836 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000837};
838
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000839PyTypeObject PyFloat_Type = {
840 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000841 0,
842 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000843 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000844 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000845 (destructor)float_dealloc, /* tp_dealloc */
846 (printfunc)float_print, /* tp_print */
847 0, /* tp_getattr */
848 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +0000849 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000850 (reprfunc)float_repr, /* tp_repr */
851 &float_as_number, /* tp_as_number */
852 0, /* tp_as_sequence */
853 0, /* tp_as_mapping */
854 (hashfunc)float_hash, /* tp_hash */
855 0, /* tp_call */
856 (reprfunc)float_str, /* tp_str */
857 PyObject_GenericGetAttr, /* tp_getattro */
858 0, /* tp_setattro */
859 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +0000860 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
861 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000862 float_doc, /* tp_doc */
863 0, /* tp_traverse */
864 0, /* tp_clear */
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000865 (richcmpfunc)float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000866 0, /* tp_weaklistoffset */
867 0, /* tp_iter */
868 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000869 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000870 0, /* tp_members */
871 0, /* tp_getset */
872 0, /* tp_base */
873 0, /* tp_dict */
874 0, /* tp_descr_get */
875 0, /* tp_descr_set */
876 0, /* tp_dictoffset */
877 0, /* tp_init */
878 0, /* tp_alloc */
879 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000880};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +0000881
882void
Fred Drakefd99de62000-07-09 05:02:18 +0000883PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +0000884{
Guido van Rossum3fce8831999-03-12 19:43:17 +0000885 PyFloatObject *p;
886 PyFloatBlock *list, *next;
Neal Norwitz739a8f82004-07-08 01:55:58 +0000887 unsigned i;
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000888 int bc, bf; /* block count, number of freed blocks */
889 int frem, fsum; /* remaining unfreed floats per block, total */
890
891 bc = 0;
892 bf = 0;
893 fsum = 0;
894 list = block_list;
895 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +0000896 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000897 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000898 bc++;
899 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +0000900 for (i = 0, p = &list->objects[0];
901 i < N_FLOATOBJECTS;
902 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +0000903 if (PyFloat_CheckExact(p) && p->ob_refcnt != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000904 frem++;
905 }
Guido van Rossum3fce8831999-03-12 19:43:17 +0000906 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000907 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +0000908 list->next = block_list;
909 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +0000910 for (i = 0, p = &list->objects[0];
911 i < N_FLOATOBJECTS;
912 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +0000913 if (!PyFloat_CheckExact(p) ||
Guido van Rossumbef14172001-08-29 15:47:46 +0000914 p->ob_refcnt == 0) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +0000915 p->ob_type = (struct _typeobject *)
916 free_list;
917 free_list = p;
918 }
919 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000920 }
921 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000922 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000923 bf++;
924 }
925 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +0000926 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000927 }
Guido van Rossum3fce8831999-03-12 19:43:17 +0000928 if (!Py_VerboseFlag)
929 return;
930 fprintf(stderr, "# cleanup floats");
931 if (!fsum) {
932 fprintf(stderr, "\n");
933 }
934 else {
935 fprintf(stderr,
936 ": %d unfreed float%s in %d out of %d block%s\n",
937 fsum, fsum == 1 ? "" : "s",
938 bc - bf, bc, bc == 1 ? "" : "s");
939 }
940 if (Py_VerboseFlag > 1) {
941 list = block_list;
942 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +0000943 for (i = 0, p = &list->objects[0];
944 i < N_FLOATOBJECTS;
945 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +0000946 if (PyFloat_CheckExact(p) &&
Guido van Rossumbef14172001-08-29 15:47:46 +0000947 p->ob_refcnt != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +0000948 char buf[100];
949 PyFloat_AsString(buf, p);
950 fprintf(stderr,
Fred Drakea44d3532000-06-30 15:01:00 +0000951 "# <float at %p, refcnt=%d, val=%s>\n",
952 p, p->ob_refcnt, buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +0000953 }
954 }
955 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000956 }
957 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +0000958}
Tim Peters9905b942003-03-20 20:53:32 +0000959
960/*----------------------------------------------------------------------------
961 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
962 *
963 * TODO: On platforms that use the standard IEEE-754 single and double
964 * formats natively, these routines could simply copy the bytes.
965 */
966int
967_PyFloat_Pack4(double x, unsigned char *p, int le)
968{
969 unsigned char sign;
970 int e;
971 double f;
972 unsigned int fbits;
973 int incr = 1;
974
975 if (le) {
976 p += 3;
977 incr = -1;
978 }
979
980 if (x < 0) {
981 sign = 1;
982 x = -x;
983 }
984 else
985 sign = 0;
986
987 f = frexp(x, &e);
988
989 /* Normalize f to be in the range [1.0, 2.0) */
990 if (0.5 <= f && f < 1.0) {
991 f *= 2.0;
992 e--;
993 }
994 else if (f == 0.0)
995 e = 0;
996 else {
997 PyErr_SetString(PyExc_SystemError,
998 "frexp() result out of range");
999 return -1;
1000 }
1001
1002 if (e >= 128)
1003 goto Overflow;
1004 else if (e < -126) {
1005 /* Gradual underflow */
1006 f = ldexp(f, 126 + e);
1007 e = 0;
1008 }
1009 else if (!(e == 0 && f == 0.0)) {
1010 e += 127;
1011 f -= 1.0; /* Get rid of leading 1 */
1012 }
1013
1014 f *= 8388608.0; /* 2**23 */
Tim Petersf1ed9342003-03-21 17:10:03 +00001015 fbits = (unsigned int)(f + 0.5); /* Round */
Tim Peters9905b942003-03-20 20:53:32 +00001016 assert(fbits <= 8388608);
1017 if (fbits >> 23) {
1018 /* The carry propagated out of a string of 23 1 bits. */
1019 fbits = 0;
1020 ++e;
1021 if (e >= 255)
1022 goto Overflow;
1023 }
1024
1025 /* First byte */
1026 *p = (sign << 7) | (e >> 1);
1027 p += incr;
1028
1029 /* Second byte */
1030 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1031 p += incr;
1032
1033 /* Third byte */
1034 *p = (fbits >> 8) & 0xFF;
1035 p += incr;
1036
1037 /* Fourth byte */
1038 *p = fbits & 0xFF;
1039
1040 /* Done */
1041 return 0;
1042
1043 Overflow:
1044 PyErr_SetString(PyExc_OverflowError,
1045 "float too large to pack with f format");
1046 return -1;
1047}
1048
1049int
1050_PyFloat_Pack8(double x, unsigned char *p, int le)
1051{
1052 unsigned char sign;
1053 int e;
1054 double f;
1055 unsigned int fhi, flo;
1056 int incr = 1;
1057
1058 if (le) {
1059 p += 7;
1060 incr = -1;
1061 }
1062
1063 if (x < 0) {
1064 sign = 1;
1065 x = -x;
1066 }
1067 else
1068 sign = 0;
1069
1070 f = frexp(x, &e);
1071
1072 /* Normalize f to be in the range [1.0, 2.0) */
1073 if (0.5 <= f && f < 1.0) {
1074 f *= 2.0;
1075 e--;
1076 }
1077 else if (f == 0.0)
1078 e = 0;
1079 else {
1080 PyErr_SetString(PyExc_SystemError,
1081 "frexp() result out of range");
1082 return -1;
1083 }
1084
1085 if (e >= 1024)
1086 goto Overflow;
1087 else if (e < -1022) {
1088 /* Gradual underflow */
1089 f = ldexp(f, 1022 + e);
1090 e = 0;
1091 }
1092 else if (!(e == 0 && f == 0.0)) {
1093 e += 1023;
1094 f -= 1.0; /* Get rid of leading 1 */
1095 }
1096
1097 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1098 f *= 268435456.0; /* 2**28 */
1099 fhi = (unsigned int)f; /* Truncate */
1100 assert(fhi < 268435456);
1101
1102 f -= (double)fhi;
1103 f *= 16777216.0; /* 2**24 */
1104 flo = (unsigned int)(f + 0.5); /* Round */
1105 assert(flo <= 16777216);
1106 if (flo >> 24) {
1107 /* The carry propagated out of a string of 24 1 bits. */
1108 flo = 0;
1109 ++fhi;
1110 if (fhi >> 28) {
1111 /* And it also progagated out of the next 28 bits. */
1112 fhi = 0;
1113 ++e;
1114 if (e >= 2047)
1115 goto Overflow;
1116 }
1117 }
1118
1119 /* First byte */
1120 *p = (sign << 7) | (e >> 4);
1121 p += incr;
1122
1123 /* Second byte */
1124 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1125 p += incr;
1126
1127 /* Third byte */
1128 *p = (fhi >> 16) & 0xFF;
1129 p += incr;
1130
1131 /* Fourth byte */
1132 *p = (fhi >> 8) & 0xFF;
1133 p += incr;
1134
1135 /* Fifth byte */
1136 *p = fhi & 0xFF;
1137 p += incr;
1138
1139 /* Sixth byte */
1140 *p = (flo >> 16) & 0xFF;
1141 p += incr;
1142
1143 /* Seventh byte */
1144 *p = (flo >> 8) & 0xFF;
1145 p += incr;
1146
1147 /* Eighth byte */
1148 *p = flo & 0xFF;
1149 p += incr;
1150
1151 /* Done */
1152 return 0;
1153
1154 Overflow:
1155 PyErr_SetString(PyExc_OverflowError,
1156 "float too large to pack with d format");
1157 return -1;
1158}
1159
1160double
1161_PyFloat_Unpack4(const unsigned char *p, int le)
1162{
1163 unsigned char sign;
1164 int e;
1165 unsigned int f;
1166 double x;
1167 int incr = 1;
1168
1169 if (le) {
1170 p += 3;
1171 incr = -1;
1172 }
1173
1174 /* First byte */
1175 sign = (*p >> 7) & 1;
1176 e = (*p & 0x7F) << 1;
1177 p += incr;
1178
1179 /* Second byte */
1180 e |= (*p >> 7) & 1;
1181 f = (*p & 0x7F) << 16;
1182 p += incr;
1183
1184 /* Third byte */
1185 f |= *p << 8;
1186 p += incr;
1187
1188 /* Fourth byte */
1189 f |= *p;
1190
1191 x = (double)f / 8388608.0;
1192
1193 /* XXX This sadly ignores Inf/NaN issues */
1194 if (e == 0)
1195 e = -126;
1196 else {
1197 x += 1.0;
1198 e -= 127;
1199 }
1200 x = ldexp(x, e);
1201
1202 if (sign)
1203 x = -x;
1204
1205 return x;
1206}
1207
1208double
1209_PyFloat_Unpack8(const unsigned char *p, int le)
1210{
1211 unsigned char sign;
1212 int e;
1213 unsigned int fhi, flo;
1214 double x;
1215 int incr = 1;
1216
1217 if (le) {
1218 p += 7;
1219 incr = -1;
1220 }
1221
1222 /* First byte */
1223 sign = (*p >> 7) & 1;
1224 e = (*p & 0x7F) << 4;
1225 p += incr;
1226
1227 /* Second byte */
1228 e |= (*p >> 4) & 0xF;
1229 fhi = (*p & 0xF) << 24;
1230 p += incr;
1231
1232 /* Third byte */
1233 fhi |= *p << 16;
1234 p += incr;
1235
1236 /* Fourth byte */
1237 fhi |= *p << 8;
1238 p += incr;
1239
1240 /* Fifth byte */
1241 fhi |= *p;
1242 p += incr;
1243
1244 /* Sixth byte */
1245 flo = *p << 16;
1246 p += incr;
1247
1248 /* Seventh byte */
1249 flo |= *p << 8;
1250 p += incr;
1251
1252 /* Eighth byte */
1253 flo |= *p;
1254
1255 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1256 x /= 268435456.0; /* 2**28 */
1257
1258 /* XXX This sadly ignores Inf/NaN */
1259 if (e == 0)
1260 e = -1022;
1261 else {
1262 x += 1.0;
1263 e -= 1023;
1264 }
1265 x = ldexp(x, e);
1266
1267 if (sign)
1268 x = -x;
1269
1270 return x;
1271}