blob: b3bcaa91ca09f3c317161acd1d09d22c525569cc [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)
Tim Petersef14d732000-09-23 03:39:17 +0000135 x = 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)
Tim Petersef14d732000-09-23 03:39:17 +0000167 x = 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;
226 /* Subroutine for float_repr and float_print.
227 We want float numbers to be recognizable as such,
228 i.e., they should contain a decimal point or an exponent.
229 However, %g may print the number as an integer;
230 in such cases, we append ".0" to the string. */
Tim Peters97019e42001-11-28 22:43:45 +0000231
232 assert(PyFloat_Check(v));
233 PyOS_snprintf(buf, buflen, "%.*g", precision, v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000234 cp = buf;
235 if (*cp == '-')
236 cp++;
237 for (; *cp != '\0'; cp++) {
238 /* Any non-digit means it's not an integer;
239 this takes care of NAN and INF as well. */
Guido van Rossum9fa2c111995-02-10 17:00:37 +0000240 if (!isdigit(Py_CHARMASK(*cp)))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000241 break;
242 }
243 if (*cp == '\0') {
244 *cp++ = '.';
245 *cp++ = '0';
246 *cp++ = '\0';
247 }
248}
249
Tim Peters97019e42001-11-28 22:43:45 +0000250/* XXX PyFloat_AsStringEx should not be a public API function (for one
251 XXX thing, its signature passes a buffer without a length; for another,
252 XXX it isn't useful outside this file).
253*/
254void
255PyFloat_AsStringEx(char *buf, PyFloatObject *v, int precision)
256{
257 format_float(buf, 100, v, precision);
258}
259
Neil Schemenauer32117e52001-01-04 01:44:34 +0000260/* Macro and helper that convert PyObject obj to a C double and store
261 the value in dbl; this replaces the functionality of the coercion
Tim Peters77d8a4f2001-12-11 20:31:34 +0000262 slot function. If conversion to double raises an exception, obj is
263 set to NULL, and the function invoking this macro returns NULL. If
264 obj is not of float, int or long type, Py_NotImplemented is incref'ed,
265 stored in obj, and returned from the function invoking this macro.
266*/
Neil Schemenauer32117e52001-01-04 01:44:34 +0000267#define CONVERT_TO_DOUBLE(obj, dbl) \
268 if (PyFloat_Check(obj)) \
269 dbl = PyFloat_AS_DOUBLE(obj); \
270 else if (convert_to_double(&(obj), &(dbl)) < 0) \
271 return obj;
272
273static int
Tim Peters9fffa3e2001-09-04 05:14:19 +0000274convert_to_double(PyObject **v, double *dbl)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000275{
276 register PyObject *obj = *v;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000277
Neil Schemenauer32117e52001-01-04 01:44:34 +0000278 if (PyInt_Check(obj)) {
279 *dbl = (double)PyInt_AS_LONG(obj);
280 }
281 else if (PyLong_Check(obj)) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000282 *dbl = PyLong_AsDouble(obj);
Tim Peters9fffa3e2001-09-04 05:14:19 +0000283 if (*dbl == -1.0 && PyErr_Occurred()) {
284 *v = NULL;
285 return -1;
286 }
Neil Schemenauer32117e52001-01-04 01:44:34 +0000287 }
288 else {
289 Py_INCREF(Py_NotImplemented);
290 *v = Py_NotImplemented;
291 return -1;
292 }
293 return 0;
294}
295
Guido van Rossum57072eb1999-12-23 19:00:28 +0000296/* Precisions used by repr() and str(), respectively.
297
298 The repr() precision (17 significant decimal digits) is the minimal number
299 that is guaranteed to have enough precision so that if the number is read
300 back in the exact same binary value is recreated. This is true for IEEE
301 floating point by design, and also happens to work for all other modern
302 hardware.
303
304 The str() precision is chosen so that in most cases, the rounding noise
305 created by various operations is suppressed, while giving plenty of
306 precision for practical use.
307
308*/
309
310#define PREC_REPR 17
311#define PREC_STR 12
312
Tim Peters97019e42001-11-28 22:43:45 +0000313/* XXX PyFloat_AsString and PyFloat_AsReprString should be deprecated:
314 XXX they pass a char buffer without passing a length.
315*/
Guido van Rossum57072eb1999-12-23 19:00:28 +0000316void
Fred Drakefd99de62000-07-09 05:02:18 +0000317PyFloat_AsString(char *buf, PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000318{
Tim Peters97019e42001-11-28 22:43:45 +0000319 format_float(buf, 100, v, PREC_STR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000320}
321
Tim Peters72f98e92001-05-08 15:19:57 +0000322void
323PyFloat_AsReprString(char *buf, PyFloatObject *v)
324{
Tim Peters97019e42001-11-28 22:43:45 +0000325 format_float(buf, 100, v, PREC_REPR);
Tim Peters72f98e92001-05-08 15:19:57 +0000326}
327
Guido van Rossum3132a5a1992-03-27 17:28:44 +0000328/* ARGSUSED */
Guido van Rossum90933611991-06-07 16:10:43 +0000329static int
Fred Drakefd99de62000-07-09 05:02:18 +0000330float_print(PyFloatObject *v, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000331{
332 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000333 format_float(buf, sizeof(buf), v,
334 (flags & Py_PRINT_RAW) ? PREC_STR : PREC_REPR);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000335 fputs(buf, fp);
Guido van Rossum90933611991-06-07 16:10:43 +0000336 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000337}
338
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000339static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000340float_repr(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000341{
342 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000343 format_float(buf, sizeof(buf), v, PREC_REPR);
Guido van Rossum57072eb1999-12-23 19:00:28 +0000344 return PyString_FromString(buf);
345}
346
347static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000348float_str(PyFloatObject *v)
Guido van Rossum57072eb1999-12-23 19:00:28 +0000349{
350 char buf[100];
Tim Peters97019e42001-11-28 22:43:45 +0000351 format_float(buf, sizeof(buf), v, PREC_STR);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000352 return PyString_FromString(buf);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000353}
354
355static int
Fred Drakefd99de62000-07-09 05:02:18 +0000356float_compare(PyFloatObject *v, PyFloatObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000357{
358 double i = v->ob_fval;
359 double j = w->ob_fval;
360 return (i < j) ? -1 : (i > j) ? 1 : 0;
361}
362
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000363static PyObject*
364float_richcompare(PyObject *v, PyObject *w, int op)
365{
366 double i, j;
367 int r = 0;
368
369 CONVERT_TO_DOUBLE(v, i);
370 CONVERT_TO_DOUBLE(w, j);
371
372 PyFPE_START_PROTECT("richcompare", return NULL)
373 switch (op) {
374 case Py_EQ:
375 r = i==j;
376 break;
377 case Py_NE:
378 r = i!=j;
379 break;
380 case Py_LE:
381 r = i<=j;
382 break;
383 case Py_GE:
384 r = i>=j;
385 break;
386 case Py_LT:
387 r = i<j;
388 break;
389 case Py_GT:
390 r = i>j;
391 break;
392 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000393 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000394 return PyBool_FromLong(r);
395}
396
Guido van Rossum9bfef441993-03-29 10:43:31 +0000397static long
Fred Drakefd99de62000-07-09 05:02:18 +0000398float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000399{
Tim Peters39dce292000-08-15 03:34:48 +0000400 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000401}
402
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000403static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000404float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000405{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000406 double a,b;
407 CONVERT_TO_DOUBLE(v, a);
408 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000409 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000410 a = a + b;
411 PyFPE_END_PROTECT(a)
412 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000413}
414
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000415static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000416float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000417{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000418 double a,b;
419 CONVERT_TO_DOUBLE(v, a);
420 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000421 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000422 a = a - b;
423 PyFPE_END_PROTECT(a)
424 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000425}
426
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000427static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000428float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000429{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000430 double a,b;
431 CONVERT_TO_DOUBLE(v, a);
432 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000433 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000434 a = a * b;
435 PyFPE_END_PROTECT(a)
436 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000437}
438
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000439static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000440float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000441{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000442 double a,b;
443 CONVERT_TO_DOUBLE(v, a);
444 CONVERT_TO_DOUBLE(w, b);
445 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000446 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000447 return NULL;
448 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000449 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000450 a = a / b;
451 PyFPE_END_PROTECT(a)
452 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000453}
454
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000456float_classic_div(PyObject *v, PyObject *w)
457{
458 double a,b;
459 CONVERT_TO_DOUBLE(v, a);
460 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000461 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000462 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
463 return NULL;
464 if (b == 0.0) {
465 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
466 return NULL;
467 }
468 PyFPE_START_PROTECT("divide", return 0)
469 a = a / b;
470 PyFPE_END_PROTECT(a)
471 return PyFloat_FromDouble(a);
472}
473
474static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000475float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000476{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000477 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000478 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000479 CONVERT_TO_DOUBLE(v, vx);
480 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000481 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000482 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000483 return NULL;
484 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000485 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000486 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000487 /* note: checking mod*wx < 0 is incorrect -- underflows to
488 0 if wx < sqrt(smallest nonzero double) */
489 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000490 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000491 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000492 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000493 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000494}
495
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000496static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000497float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000498{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000499 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000500 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000501 CONVERT_TO_DOUBLE(v, vx);
502 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000503 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000504 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000505 return NULL;
506 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000507 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000508 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000509 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000510 exact multiple of wx. But this is fp arithmetic, and fp
511 vx - mod is an approximation; the result is that div may
512 not be an exact integral value after the division, although
513 it will always be very close to one.
514 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000515 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000516 if (mod) {
517 /* ensure the remainder has the same sign as the denominator */
518 if ((wx < 0) != (mod < 0)) {
519 mod += wx;
520 div -= 1.0;
521 }
522 }
523 else {
524 /* the remainder is zero, and in the presence of signed zeroes
525 fmod returns different results across platforms; ensure
526 it has the same sign as the denominator; we'd like to do
527 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000528 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000529 if (wx < 0.0)
530 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000531 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000532 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000533 if (div) {
534 floordiv = floor(div);
535 if (div - floordiv > 0.5)
536 floordiv += 1.0;
537 }
538 else {
539 /* div is zero - get the same sign as the true quotient */
540 div *= div; /* hide "div = +0" from optimizers */
541 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
542 }
543 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000544 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000545}
546
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000547static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000548float_floor_div(PyObject *v, PyObject *w)
549{
550 PyObject *t, *r;
551
552 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000553 if (t == NULL || t == Py_NotImplemented)
554 return t;
555 assert(PyTuple_CheckExact(t));
556 r = PyTuple_GET_ITEM(t, 0);
557 Py_INCREF(r);
558 Py_DECREF(t);
559 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000560}
561
562static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000563float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000564{
565 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000566
567 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000568 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000569 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000570 return NULL;
571 }
572
Neil Schemenauer32117e52001-01-04 01:44:34 +0000573 CONVERT_TO_DOUBLE(v, iv);
574 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000575
576 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000577 if (iw == 0) { /* v**0 is 1, even 0**0 */
Tim Petersc54d1902000-10-06 00:36:09 +0000578 PyFPE_START_PROTECT("pow", return NULL)
579 if ((PyObject *)z != Py_None) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000580 double iz;
Neil Schemenauer010b0cc2001-01-08 06:29:50 +0000581 CONVERT_TO_DOUBLE(z, iz);
Tim Peters96685bf2001-08-23 22:31:37 +0000582 ix = fmod(1.0, iz);
583 if (ix != 0 && iz < 0)
584 ix += iz;
Guido van Rossum70d93461991-05-28 21:57:39 +0000585 }
Tim Petersc54d1902000-10-06 00:36:09 +0000586 else
587 ix = 1.0;
588 PyFPE_END_PROTECT(ix)
Tim Petersd2364e82001-11-01 20:09:42 +0000589 return PyFloat_FromDouble(ix);
Tim Petersc54d1902000-10-06 00:36:09 +0000590 }
Tim Peters96685bf2001-08-23 22:31:37 +0000591 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000592 if (iw < 0.0) {
593 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000594 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000595 return NULL;
596 }
597 return PyFloat_FromDouble(0.0);
598 }
Tim Peterse87568d2003-05-24 20:18:24 +0000599 if (iv < 0.0) {
600 /* Whether this is an error is a mess, and bumps into libm
601 * bugs so we have to figure it out ourselves.
602 */
603 if (iw != floor(iw)) {
604 PyErr_SetString(PyExc_ValueError, "negative number "
605 "cannot be raised to a fractional power");
606 return NULL;
607 }
608 /* iw is an exact integer, albeit perhaps a very large one.
609 * -1 raised to an exact integer should never be exceptional.
610 * Alas, some libms (chiefly glibc as of early 2003) return
611 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
612 * happen to be representable in a *C* integer. That's a
613 * bug; we let that slide in math.pow() (which currently
614 * reflects all platform accidents), but not for Python's **.
615 */
616 if (iv == -1.0 && !Py_IS_INFINITY(iw) && iw == iw) {
617 /* XXX the "iw == iw" was to weed out NaNs. This
618 * XXX doesn't actually work on all platforms.
619 */
620 /* Return 1 if iw is even, -1 if iw is odd; there's
621 * no guarantee that any C integral type is big
622 * enough to hold iw, so we have to check this
623 * indirectly.
624 */
625 ix = floor(iw * 0.5) * 2.0;
626 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
627 }
628 /* Else iv != -1.0, and overflow or underflow are possible.
629 * Unless we're to write pow() ourselves, we have to trust
630 * the platform to do this correctly.
631 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000632 }
Tim Peters96685bf2001-08-23 22:31:37 +0000633 errno = 0;
634 PyFPE_START_PROTECT("pow", return NULL)
635 ix = pow(iv, iw);
636 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000637 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000638 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000639 /* We don't expect any errno value other than ERANGE, but
640 * the range of libm bugs appears unbounded.
641 */
642 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
643 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000644 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000645 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000646 return PyFloat_FromDouble(ix);
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_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000651{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000652 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000653}
654
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000655static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000656float_pos(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000657{
Tim Peters0280cf72001-09-11 21:53:35 +0000658 if (PyFloat_CheckExact(v)) {
659 Py_INCREF(v);
660 return (PyObject *)v;
661 }
662 else
663 return PyFloat_FromDouble(v->ob_fval);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000664}
665
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000666static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000667float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000668{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000669 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000670}
671
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000672static int
Fred Drakefd99de62000-07-09 05:02:18 +0000673float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000674{
675 return v->ob_fval != 0.0;
676}
677
Guido van Rossum234f9421993-06-17 12:35:49 +0000678static int
Fred Drakefd99de62000-07-09 05:02:18 +0000679float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +0000680{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000681 if (PyInt_Check(*pw)) {
682 long x = PyInt_AsLong(*pw);
683 *pw = PyFloat_FromDouble((double)x);
684 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000685 return 0;
686 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000687 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +0000688 double x = PyLong_AsDouble(*pw);
689 if (x == -1.0 && PyErr_Occurred())
690 return -1;
691 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000692 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000693 return 0;
694 }
Guido van Rossum1952e382001-09-19 01:25:16 +0000695 else if (PyFloat_Check(*pw)) {
696 Py_INCREF(*pv);
697 Py_INCREF(*pw);
698 return 0;
699 }
Guido van Rossume6eefc21992-08-14 12:06:52 +0000700 return 1; /* Can't do it */
701}
702
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000703static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +0000704float_long(PyObject *v)
705{
706 double x = PyFloat_AsDouble(v);
707 return PyLong_FromDouble(x);
708}
709
710static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000711float_int(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000712{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000713 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000714 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000715
716 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000717 /* Try to get out cheap if this fits in a Python int. The attempt
718 * to cast to long must be protected, as C doesn't define what
719 * happens if the double is too big to fit in a long. Some rare
720 * systems raise an exception then (RISCOS was mentioned as one,
721 * and someone using a non-default option on Sun also bumped into
722 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
723 * still be vulnerable: if a long has more bits of precision than
724 * a double, casting MIN/MAX to double may yield an approximation,
725 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
726 * yield true from the C expression wholepart<=LONG_MAX, despite
727 * that wholepart is actually greater than LONG_MAX.
728 */
729 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
730 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000731 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000732 }
733 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000734}
735
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000736static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000737float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000738{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000739 Py_INCREF(v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000740 return v;
741}
742
743
Jeremy Hylton938ace62002-07-17 16:30:39 +0000744static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +0000745float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
746
Tim Peters6d6c1a32001-08-02 04:15:00 +0000747static PyObject *
748float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
749{
750 PyObject *x = Py_False; /* Integer zero */
751 static char *kwlist[] = {"x", 0};
752
Guido van Rossumbef14172001-08-29 15:47:46 +0000753 if (type != &PyFloat_Type)
754 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000755 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
756 return NULL;
757 if (PyString_Check(x))
758 return PyFloat_FromString(x, NULL);
759 return PyNumber_Float(x);
760}
761
Guido van Rossumbef14172001-08-29 15:47:46 +0000762/* Wimpy, slow approach to tp_new calls for subtypes of float:
763 first create a regular float from whatever arguments we got,
764 then allocate a subtype instance and initialize its ob_fval
765 from the regular float. The regular float is then thrown away.
766*/
767static PyObject *
768float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
769{
770 PyObject *tmp, *new;
771
772 assert(PyType_IsSubtype(type, &PyFloat_Type));
773 tmp = float_new(&PyFloat_Type, args, kwds);
774 if (tmp == NULL)
775 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +0000776 assert(PyFloat_CheckExact(tmp));
Guido van Rossumd93dce12001-08-30 03:09:31 +0000777 new = type->tp_alloc(type, 0);
Raymond Hettingerf4667932003-06-28 20:04:25 +0000778 if (new == NULL) {
779 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +0000780 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +0000781 }
Guido van Rossumbef14172001-08-29 15:47:46 +0000782 ((PyFloatObject *)new)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
783 Py_DECREF(tmp);
784 return new;
785}
786
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000787static PyObject *
788float_getnewargs(PyFloatObject *v)
789{
790 return Py_BuildValue("(d)", v->ob_fval);
791}
792
793static PyMethodDef float_methods[] = {
794 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
795 {NULL, NULL} /* sentinel */
796};
797
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000798PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000799"float(x) -> floating point number\n\
800\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000801Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000802
803
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000804static PyNumberMethods float_as_number = {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000805 (binaryfunc)float_add, /*nb_add*/
806 (binaryfunc)float_sub, /*nb_subtract*/
807 (binaryfunc)float_mul, /*nb_multiply*/
Guido van Rossum393661d2001-08-31 17:40:15 +0000808 (binaryfunc)float_classic_div, /*nb_divide*/
Guido van Rossumb6775db1994-08-01 11:34:53 +0000809 (binaryfunc)float_rem, /*nb_remainder*/
810 (binaryfunc)float_divmod, /*nb_divmod*/
Guido van Rossum0b7d02a1994-08-12 12:52:35 +0000811 (ternaryfunc)float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +0000812 (unaryfunc)float_neg, /*nb_negative*/
813 (unaryfunc)float_pos, /*nb_positive*/
814 (unaryfunc)float_abs, /*nb_absolute*/
815 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +0000816 0, /*nb_invert*/
817 0, /*nb_lshift*/
818 0, /*nb_rshift*/
819 0, /*nb_and*/
820 0, /*nb_xor*/
821 0, /*nb_or*/
Guido van Rossumb6775db1994-08-01 11:34:53 +0000822 (coercion)float_coerce, /*nb_coerce*/
823 (unaryfunc)float_int, /*nb_int*/
824 (unaryfunc)float_long, /*nb_long*/
825 (unaryfunc)float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +0000826 0, /* nb_oct */
827 0, /* nb_hex */
828 0, /* nb_inplace_add */
829 0, /* nb_inplace_subtract */
830 0, /* nb_inplace_multiply */
831 0, /* nb_inplace_divide */
832 0, /* nb_inplace_remainder */
833 0, /* nb_inplace_power */
834 0, /* nb_inplace_lshift */
835 0, /* nb_inplace_rshift */
836 0, /* nb_inplace_and */
837 0, /* nb_inplace_xor */
838 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +0000839 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +0000840 float_div, /* nb_true_divide */
841 0, /* nb_inplace_floor_divide */
842 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000843};
844
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000845PyTypeObject PyFloat_Type = {
846 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000847 0,
848 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000849 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000850 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000851 (destructor)float_dealloc, /* tp_dealloc */
852 (printfunc)float_print, /* tp_print */
853 0, /* tp_getattr */
854 0, /* tp_setattr */
Michael W. Hudson6bee23c2004-02-26 13:16:03 +0000855 (cmpfunc)float_compare, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000856 (reprfunc)float_repr, /* tp_repr */
857 &float_as_number, /* tp_as_number */
858 0, /* tp_as_sequence */
859 0, /* tp_as_mapping */
860 (hashfunc)float_hash, /* tp_hash */
861 0, /* tp_call */
862 (reprfunc)float_str, /* tp_str */
863 PyObject_GenericGetAttr, /* tp_getattro */
864 0, /* tp_setattro */
865 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +0000866 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
867 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000868 float_doc, /* tp_doc */
869 0, /* tp_traverse */
870 0, /* tp_clear */
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000871 (richcmpfunc)float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000872 0, /* tp_weaklistoffset */
873 0, /* tp_iter */
874 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000875 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000876 0, /* tp_members */
877 0, /* tp_getset */
878 0, /* tp_base */
879 0, /* tp_dict */
880 0, /* tp_descr_get */
881 0, /* tp_descr_set */
882 0, /* tp_dictoffset */
883 0, /* tp_init */
884 0, /* tp_alloc */
885 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000886};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +0000887
888void
Fred Drakefd99de62000-07-09 05:02:18 +0000889PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +0000890{
Guido van Rossum3fce8831999-03-12 19:43:17 +0000891 PyFloatObject *p;
892 PyFloatBlock *list, *next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000893 int i;
894 int bc, bf; /* block count, number of freed blocks */
895 int frem, fsum; /* remaining unfreed floats per block, total */
896
897 bc = 0;
898 bf = 0;
899 fsum = 0;
900 list = block_list;
901 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +0000902 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000903 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000904 bc++;
905 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +0000906 for (i = 0, p = &list->objects[0];
907 i < N_FLOATOBJECTS;
908 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +0000909 if (PyFloat_CheckExact(p) && p->ob_refcnt != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000910 frem++;
911 }
Guido van Rossum3fce8831999-03-12 19:43:17 +0000912 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000913 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +0000914 list->next = block_list;
915 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +0000916 for (i = 0, p = &list->objects[0];
917 i < N_FLOATOBJECTS;
918 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +0000919 if (!PyFloat_CheckExact(p) ||
Guido van Rossumbef14172001-08-29 15:47:46 +0000920 p->ob_refcnt == 0) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +0000921 p->ob_type = (struct _typeobject *)
922 free_list;
923 free_list = p;
924 }
925 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000926 }
927 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000928 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000929 bf++;
930 }
931 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +0000932 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000933 }
Guido van Rossum3fce8831999-03-12 19:43:17 +0000934 if (!Py_VerboseFlag)
935 return;
936 fprintf(stderr, "# cleanup floats");
937 if (!fsum) {
938 fprintf(stderr, "\n");
939 }
940 else {
941 fprintf(stderr,
942 ": %d unfreed float%s in %d out of %d block%s\n",
943 fsum, fsum == 1 ? "" : "s",
944 bc - bf, bc, bc == 1 ? "" : "s");
945 }
946 if (Py_VerboseFlag > 1) {
947 list = block_list;
948 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +0000949 for (i = 0, p = &list->objects[0];
950 i < N_FLOATOBJECTS;
951 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +0000952 if (PyFloat_CheckExact(p) &&
Guido van Rossumbef14172001-08-29 15:47:46 +0000953 p->ob_refcnt != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +0000954 char buf[100];
955 PyFloat_AsString(buf, p);
956 fprintf(stderr,
Fred Drakea44d3532000-06-30 15:01:00 +0000957 "# <float at %p, refcnt=%d, val=%s>\n",
958 p, p->ob_refcnt, buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +0000959 }
960 }
961 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000962 }
963 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +0000964}
Tim Peters9905b942003-03-20 20:53:32 +0000965
966/*----------------------------------------------------------------------------
967 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
968 *
969 * TODO: On platforms that use the standard IEEE-754 single and double
970 * formats natively, these routines could simply copy the bytes.
971 */
972int
973_PyFloat_Pack4(double x, unsigned char *p, int le)
974{
975 unsigned char sign;
976 int e;
977 double f;
978 unsigned int fbits;
979 int incr = 1;
980
981 if (le) {
982 p += 3;
983 incr = -1;
984 }
985
986 if (x < 0) {
987 sign = 1;
988 x = -x;
989 }
990 else
991 sign = 0;
992
993 f = frexp(x, &e);
994
995 /* Normalize f to be in the range [1.0, 2.0) */
996 if (0.5 <= f && f < 1.0) {
997 f *= 2.0;
998 e--;
999 }
1000 else if (f == 0.0)
1001 e = 0;
1002 else {
1003 PyErr_SetString(PyExc_SystemError,
1004 "frexp() result out of range");
1005 return -1;
1006 }
1007
1008 if (e >= 128)
1009 goto Overflow;
1010 else if (e < -126) {
1011 /* Gradual underflow */
1012 f = ldexp(f, 126 + e);
1013 e = 0;
1014 }
1015 else if (!(e == 0 && f == 0.0)) {
1016 e += 127;
1017 f -= 1.0; /* Get rid of leading 1 */
1018 }
1019
1020 f *= 8388608.0; /* 2**23 */
Tim Petersf1ed9342003-03-21 17:10:03 +00001021 fbits = (unsigned int)(f + 0.5); /* Round */
Tim Peters9905b942003-03-20 20:53:32 +00001022 assert(fbits <= 8388608);
1023 if (fbits >> 23) {
1024 /* The carry propagated out of a string of 23 1 bits. */
1025 fbits = 0;
1026 ++e;
1027 if (e >= 255)
1028 goto Overflow;
1029 }
1030
1031 /* First byte */
1032 *p = (sign << 7) | (e >> 1);
1033 p += incr;
1034
1035 /* Second byte */
1036 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1037 p += incr;
1038
1039 /* Third byte */
1040 *p = (fbits >> 8) & 0xFF;
1041 p += incr;
1042
1043 /* Fourth byte */
1044 *p = fbits & 0xFF;
1045
1046 /* Done */
1047 return 0;
1048
1049 Overflow:
1050 PyErr_SetString(PyExc_OverflowError,
1051 "float too large to pack with f format");
1052 return -1;
1053}
1054
1055int
1056_PyFloat_Pack8(double x, unsigned char *p, int le)
1057{
1058 unsigned char sign;
1059 int e;
1060 double f;
1061 unsigned int fhi, flo;
1062 int incr = 1;
1063
1064 if (le) {
1065 p += 7;
1066 incr = -1;
1067 }
1068
1069 if (x < 0) {
1070 sign = 1;
1071 x = -x;
1072 }
1073 else
1074 sign = 0;
1075
1076 f = frexp(x, &e);
1077
1078 /* Normalize f to be in the range [1.0, 2.0) */
1079 if (0.5 <= f && f < 1.0) {
1080 f *= 2.0;
1081 e--;
1082 }
1083 else if (f == 0.0)
1084 e = 0;
1085 else {
1086 PyErr_SetString(PyExc_SystemError,
1087 "frexp() result out of range");
1088 return -1;
1089 }
1090
1091 if (e >= 1024)
1092 goto Overflow;
1093 else if (e < -1022) {
1094 /* Gradual underflow */
1095 f = ldexp(f, 1022 + e);
1096 e = 0;
1097 }
1098 else if (!(e == 0 && f == 0.0)) {
1099 e += 1023;
1100 f -= 1.0; /* Get rid of leading 1 */
1101 }
1102
1103 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1104 f *= 268435456.0; /* 2**28 */
1105 fhi = (unsigned int)f; /* Truncate */
1106 assert(fhi < 268435456);
1107
1108 f -= (double)fhi;
1109 f *= 16777216.0; /* 2**24 */
1110 flo = (unsigned int)(f + 0.5); /* Round */
1111 assert(flo <= 16777216);
1112 if (flo >> 24) {
1113 /* The carry propagated out of a string of 24 1 bits. */
1114 flo = 0;
1115 ++fhi;
1116 if (fhi >> 28) {
1117 /* And it also progagated out of the next 28 bits. */
1118 fhi = 0;
1119 ++e;
1120 if (e >= 2047)
1121 goto Overflow;
1122 }
1123 }
1124
1125 /* First byte */
1126 *p = (sign << 7) | (e >> 4);
1127 p += incr;
1128
1129 /* Second byte */
1130 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1131 p += incr;
1132
1133 /* Third byte */
1134 *p = (fhi >> 16) & 0xFF;
1135 p += incr;
1136
1137 /* Fourth byte */
1138 *p = (fhi >> 8) & 0xFF;
1139 p += incr;
1140
1141 /* Fifth byte */
1142 *p = fhi & 0xFF;
1143 p += incr;
1144
1145 /* Sixth byte */
1146 *p = (flo >> 16) & 0xFF;
1147 p += incr;
1148
1149 /* Seventh byte */
1150 *p = (flo >> 8) & 0xFF;
1151 p += incr;
1152
1153 /* Eighth byte */
1154 *p = flo & 0xFF;
1155 p += incr;
1156
1157 /* Done */
1158 return 0;
1159
1160 Overflow:
1161 PyErr_SetString(PyExc_OverflowError,
1162 "float too large to pack with d format");
1163 return -1;
1164}
1165
1166double
1167_PyFloat_Unpack4(const unsigned char *p, int le)
1168{
1169 unsigned char sign;
1170 int e;
1171 unsigned int f;
1172 double x;
1173 int incr = 1;
1174
1175 if (le) {
1176 p += 3;
1177 incr = -1;
1178 }
1179
1180 /* First byte */
1181 sign = (*p >> 7) & 1;
1182 e = (*p & 0x7F) << 1;
1183 p += incr;
1184
1185 /* Second byte */
1186 e |= (*p >> 7) & 1;
1187 f = (*p & 0x7F) << 16;
1188 p += incr;
1189
1190 /* Third byte */
1191 f |= *p << 8;
1192 p += incr;
1193
1194 /* Fourth byte */
1195 f |= *p;
1196
1197 x = (double)f / 8388608.0;
1198
1199 /* XXX This sadly ignores Inf/NaN issues */
1200 if (e == 0)
1201 e = -126;
1202 else {
1203 x += 1.0;
1204 e -= 127;
1205 }
1206 x = ldexp(x, e);
1207
1208 if (sign)
1209 x = -x;
1210
1211 return x;
1212}
1213
1214double
1215_PyFloat_Unpack8(const unsigned char *p, int le)
1216{
1217 unsigned char sign;
1218 int e;
1219 unsigned int fhi, flo;
1220 double x;
1221 int incr = 1;
1222
1223 if (le) {
1224 p += 7;
1225 incr = -1;
1226 }
1227
1228 /* First byte */
1229 sign = (*p >> 7) & 1;
1230 e = (*p & 0x7F) << 4;
1231 p += incr;
1232
1233 /* Second byte */
1234 e |= (*p >> 4) & 0xF;
1235 fhi = (*p & 0xF) << 24;
1236 p += incr;
1237
1238 /* Third byte */
1239 fhi |= *p << 16;
1240 p += incr;
1241
1242 /* Fourth byte */
1243 fhi |= *p << 8;
1244 p += incr;
1245
1246 /* Fifth byte */
1247 fhi |= *p;
1248 p += incr;
1249
1250 /* Sixth byte */
1251 flo = *p << 16;
1252 p += incr;
1253
1254 /* Seventh byte */
1255 flo |= *p << 8;
1256 p += incr;
1257
1258 /* Eighth byte */
1259 flo |= *p;
1260
1261 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1262 x /= 268435456.0; /* 2**28 */
1263
1264 /* XXX This sadly ignores Inf/NaN */
1265 if (e == 0)
1266 e = -1022;
1267 else {
1268 x += 1.0;
1269 e -= 1023;
1270 }
1271 x = ldexp(x, e);
1272
1273 if (sign)
1274 x = -x;
1275
1276 return x;
1277}