blob: f1c8e4244e340f6679ef0ae5b0fd14c60e9a3a67 [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
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000355static PyObject*
356float_richcompare(PyObject *v, PyObject *w, int op)
357{
358 double i, j;
359 int r = 0;
360
361 CONVERT_TO_DOUBLE(v, i);
362 CONVERT_TO_DOUBLE(w, j);
363
364 PyFPE_START_PROTECT("richcompare", return NULL)
365 switch (op) {
366 case Py_EQ:
367 r = i==j;
368 break;
369 case Py_NE:
370 r = i!=j;
371 break;
372 case Py_LE:
373 r = i<=j;
374 break;
375 case Py_GE:
376 r = i>=j;
377 break;
378 case Py_LT:
379 r = i<j;
380 break;
381 case Py_GT:
382 r = i>j;
383 break;
384 }
Michael W. Hudson957f9772004-02-26 12:33:09 +0000385 PyFPE_END_PROTECT(r)
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000386 return PyBool_FromLong(r);
387}
388
Guido van Rossum9bfef441993-03-29 10:43:31 +0000389static long
Fred Drakefd99de62000-07-09 05:02:18 +0000390float_hash(PyFloatObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000391{
Tim Peters39dce292000-08-15 03:34:48 +0000392 return _Py_HashDouble(v->ob_fval);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000393}
394
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000395static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000396float_add(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000397{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000398 double a,b;
399 CONVERT_TO_DOUBLE(v, a);
400 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000401 PyFPE_START_PROTECT("add", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000402 a = a + b;
403 PyFPE_END_PROTECT(a)
404 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000405}
406
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000407static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000408float_sub(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000409{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000410 double a,b;
411 CONVERT_TO_DOUBLE(v, a);
412 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000413 PyFPE_START_PROTECT("subtract", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000414 a = a - b;
415 PyFPE_END_PROTECT(a)
416 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000417}
418
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000419static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000420float_mul(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000421{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000422 double a,b;
423 CONVERT_TO_DOUBLE(v, a);
424 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000425 PyFPE_START_PROTECT("multiply", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000426 a = a * b;
427 PyFPE_END_PROTECT(a)
428 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000429}
430
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000431static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000432float_div(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000433{
Neil Schemenauer32117e52001-01-04 01:44:34 +0000434 double a,b;
435 CONVERT_TO_DOUBLE(v, a);
436 CONVERT_TO_DOUBLE(w, b);
437 if (b == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000438 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000439 return NULL;
440 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000441 PyFPE_START_PROTECT("divide", return 0)
Neil Schemenauer32117e52001-01-04 01:44:34 +0000442 a = a / b;
443 PyFPE_END_PROTECT(a)
444 return PyFloat_FromDouble(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000445}
446
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000447static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +0000448float_classic_div(PyObject *v, PyObject *w)
449{
450 double a,b;
451 CONVERT_TO_DOUBLE(v, a);
452 CONVERT_TO_DOUBLE(w, b);
Guido van Rossum1832de42001-09-04 03:51:09 +0000453 if (Py_DivisionWarningFlag >= 2 &&
Guido van Rossum393661d2001-08-31 17:40:15 +0000454 PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
455 return NULL;
456 if (b == 0.0) {
457 PyErr_SetString(PyExc_ZeroDivisionError, "float division");
458 return NULL;
459 }
460 PyFPE_START_PROTECT("divide", return 0)
461 a = a / b;
462 PyFPE_END_PROTECT(a)
463 return PyFloat_FromDouble(a);
464}
465
466static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000467float_rem(PyObject *v, PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000468{
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000469 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000470 double mod;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000471 CONVERT_TO_DOUBLE(v, vx);
472 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000473 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000474 PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000475 return NULL;
476 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000477 PyFPE_START_PROTECT("modulo", return 0)
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000478 mod = fmod(vx, wx);
Guido van Rossum9263e781999-05-06 14:26:34 +0000479 /* note: checking mod*wx < 0 is incorrect -- underflows to
480 0 if wx < sqrt(smallest nonzero double) */
481 if (mod && ((wx < 0) != (mod < 0))) {
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000482 mod += wx;
Guido van Rossum56cd67a1992-01-26 18:16:35 +0000483 }
Guido van Rossum45b83911997-03-14 04:32:50 +0000484 PyFPE_END_PROTECT(mod)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000485 return PyFloat_FromDouble(mod);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000486}
487
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000488static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000489float_divmod(PyObject *v, PyObject *w)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000490{
Guido van Rossum15ecff41991-10-20 20:16:45 +0000491 double vx, wx;
Guido van Rossum9263e781999-05-06 14:26:34 +0000492 double div, mod, floordiv;
Neil Schemenauer32117e52001-01-04 01:44:34 +0000493 CONVERT_TO_DOUBLE(v, vx);
494 CONVERT_TO_DOUBLE(w, wx);
Guido van Rossum15ecff41991-10-20 20:16:45 +0000495 if (wx == 0.0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000496 PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
Guido van Rossum15ecff41991-10-20 20:16:45 +0000497 return NULL;
498 }
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000499 PyFPE_START_PROTECT("divmod", return 0)
Guido van Rossum15ecff41991-10-20 20:16:45 +0000500 mod = fmod(vx, wx);
Tim Peters78fc0b52000-09-16 03:54:24 +0000501 /* fmod is typically exact, so vx-mod is *mathematically* an
Guido van Rossum9263e781999-05-06 14:26:34 +0000502 exact multiple of wx. But this is fp arithmetic, and fp
503 vx - mod is an approximation; the result is that div may
504 not be an exact integral value after the division, although
505 it will always be very close to one.
506 */
Guido van Rossum15ecff41991-10-20 20:16:45 +0000507 div = (vx - mod) / wx;
Tim Petersd2e40d62001-11-01 23:12:27 +0000508 if (mod) {
509 /* ensure the remainder has the same sign as the denominator */
510 if ((wx < 0) != (mod < 0)) {
511 mod += wx;
512 div -= 1.0;
513 }
514 }
515 else {
516 /* the remainder is zero, and in the presence of signed zeroes
517 fmod returns different results across platforms; ensure
518 it has the same sign as the denominator; we'd like to do
519 "mod = wx * 0.0", but that may get optimized away */
Tim Peters4e8ab5d2001-11-01 23:59:56 +0000520 mod *= mod; /* hide "mod = +0" from optimizer */
Tim Petersd2e40d62001-11-01 23:12:27 +0000521 if (wx < 0.0)
522 mod = -mod;
Guido van Rossum15ecff41991-10-20 20:16:45 +0000523 }
Guido van Rossum9263e781999-05-06 14:26:34 +0000524 /* snap quotient to nearest integral value */
Tim Petersd2e40d62001-11-01 23:12:27 +0000525 if (div) {
526 floordiv = floor(div);
527 if (div - floordiv > 0.5)
528 floordiv += 1.0;
529 }
530 else {
531 /* div is zero - get the same sign as the true quotient */
532 div *= div; /* hide "div = +0" from optimizers */
533 floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
534 }
535 PyFPE_END_PROTECT(floordiv)
Guido van Rossum9263e781999-05-06 14:26:34 +0000536 return Py_BuildValue("(dd)", floordiv, mod);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000537}
538
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000539static PyObject *
Tim Peters63a35712001-12-11 19:57:24 +0000540float_floor_div(PyObject *v, PyObject *w)
541{
542 PyObject *t, *r;
543
544 t = float_divmod(v, w);
Tim Peters77d8a4f2001-12-11 20:31:34 +0000545 if (t == NULL || t == Py_NotImplemented)
546 return t;
547 assert(PyTuple_CheckExact(t));
548 r = PyTuple_GET_ITEM(t, 0);
549 Py_INCREF(r);
550 Py_DECREF(t);
551 return r;
Tim Peters63a35712001-12-11 19:57:24 +0000552}
553
554static PyObject *
Neil Schemenauer32117e52001-01-04 01:44:34 +0000555float_pow(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000556{
557 double iv, iw, ix;
Tim Peters32f453e2001-09-03 08:35:41 +0000558
559 if ((PyObject *)z != Py_None) {
Tim Peters4c483c42001-09-05 06:24:58 +0000560 PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
Tim Peters97f4a332001-09-05 23:49:24 +0000561 "allowed unless all arguments are integers");
Tim Peters32f453e2001-09-03 08:35:41 +0000562 return NULL;
563 }
564
Neil Schemenauer32117e52001-01-04 01:44:34 +0000565 CONVERT_TO_DOUBLE(v, iv);
566 CONVERT_TO_DOUBLE(w, iw);
Tim Petersc54d1902000-10-06 00:36:09 +0000567
568 /* Sort out special cases here instead of relying on pow() */
Tim Peters96685bf2001-08-23 22:31:37 +0000569 if (iw == 0) { /* v**0 is 1, even 0**0 */
Tim Petersc54d1902000-10-06 00:36:09 +0000570 PyFPE_START_PROTECT("pow", return NULL)
571 if ((PyObject *)z != Py_None) {
Neil Schemenauer32117e52001-01-04 01:44:34 +0000572 double iz;
Neil Schemenauer010b0cc2001-01-08 06:29:50 +0000573 CONVERT_TO_DOUBLE(z, iz);
Tim Peters96685bf2001-08-23 22:31:37 +0000574 ix = fmod(1.0, iz);
575 if (ix != 0 && iz < 0)
576 ix += iz;
Guido van Rossum70d93461991-05-28 21:57:39 +0000577 }
Tim Petersc54d1902000-10-06 00:36:09 +0000578 else
579 ix = 1.0;
580 PyFPE_END_PROTECT(ix)
Tim Petersd2364e82001-11-01 20:09:42 +0000581 return PyFloat_FromDouble(ix);
Tim Petersc54d1902000-10-06 00:36:09 +0000582 }
Tim Peters96685bf2001-08-23 22:31:37 +0000583 if (iv == 0.0) { /* 0**w is error if w<0, else 1 */
Tim Petersc54d1902000-10-06 00:36:09 +0000584 if (iw < 0.0) {
585 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +0000586 "0.0 cannot be raised to a negative power");
Tim Petersc54d1902000-10-06 00:36:09 +0000587 return NULL;
588 }
589 return PyFloat_FromDouble(0.0);
590 }
Tim Peterse87568d2003-05-24 20:18:24 +0000591 if (iv < 0.0) {
592 /* Whether this is an error is a mess, and bumps into libm
593 * bugs so we have to figure it out ourselves.
594 */
595 if (iw != floor(iw)) {
596 PyErr_SetString(PyExc_ValueError, "negative number "
597 "cannot be raised to a fractional power");
598 return NULL;
599 }
600 /* iw is an exact integer, albeit perhaps a very large one.
601 * -1 raised to an exact integer should never be exceptional.
602 * Alas, some libms (chiefly glibc as of early 2003) return
603 * NaN and set EDOM on pow(-1, large_int) if the int doesn't
604 * happen to be representable in a *C* integer. That's a
605 * bug; we let that slide in math.pow() (which currently
606 * reflects all platform accidents), but not for Python's **.
607 */
608 if (iv == -1.0 && !Py_IS_INFINITY(iw) && iw == iw) {
609 /* XXX the "iw == iw" was to weed out NaNs. This
610 * XXX doesn't actually work on all platforms.
611 */
612 /* Return 1 if iw is even, -1 if iw is odd; there's
613 * no guarantee that any C integral type is big
614 * enough to hold iw, so we have to check this
615 * indirectly.
616 */
617 ix = floor(iw * 0.5) * 2.0;
618 return PyFloat_FromDouble(ix == iw ? 1.0 : -1.0);
619 }
620 /* Else iv != -1.0, and overflow or underflow are possible.
621 * Unless we're to write pow() ourselves, we have to trust
622 * the platform to do this correctly.
623 */
Guido van Rossum86c04c21996-08-09 20:50:14 +0000624 }
Tim Peters96685bf2001-08-23 22:31:37 +0000625 errno = 0;
626 PyFPE_START_PROTECT("pow", return NULL)
627 ix = pow(iv, iw);
628 PyFPE_END_PROTECT(ix)
Tim Petersdc5a5082002-03-09 04:58:24 +0000629 Py_ADJUST_ERANGE1(ix);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000630 if (errno != 0) {
Tim Peterse87568d2003-05-24 20:18:24 +0000631 /* We don't expect any errno value other than ERANGE, but
632 * the range of libm bugs appears unbounded.
633 */
634 PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
635 PyExc_ValueError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000636 return NULL;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000637 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000638 return PyFloat_FromDouble(ix);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000639}
640
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000641static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000642float_neg(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000643{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000644 return PyFloat_FromDouble(-v->ob_fval);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000645}
646
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000647static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000648float_pos(PyFloatObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000649{
Tim Peters0280cf72001-09-11 21:53:35 +0000650 if (PyFloat_CheckExact(v)) {
651 Py_INCREF(v);
652 return (PyObject *)v;
653 }
654 else
655 return PyFloat_FromDouble(v->ob_fval);
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000656}
657
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000658static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000659float_abs(PyFloatObject *v)
Guido van Rossumeba1b5e1991-05-05 20:07:00 +0000660{
Tim Petersfaf0cd22001-11-01 21:51:15 +0000661 return PyFloat_FromDouble(fabs(v->ob_fval));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000662}
663
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000664static int
Fred Drakefd99de62000-07-09 05:02:18 +0000665float_nonzero(PyFloatObject *v)
Guido van Rossum50b4ef61991-05-14 11:57:01 +0000666{
667 return v->ob_fval != 0.0;
668}
669
Guido van Rossum234f9421993-06-17 12:35:49 +0000670static int
Fred Drakefd99de62000-07-09 05:02:18 +0000671float_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +0000672{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000673 if (PyInt_Check(*pw)) {
674 long x = PyInt_AsLong(*pw);
675 *pw = PyFloat_FromDouble((double)x);
676 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000677 return 0;
678 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000679 else if (PyLong_Check(*pw)) {
Neal Norwitzabcb0c02003-01-28 19:21:24 +0000680 double x = PyLong_AsDouble(*pw);
681 if (x == -1.0 && PyErr_Occurred())
682 return -1;
683 *pw = PyFloat_FromDouble(x);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000684 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +0000685 return 0;
686 }
Guido van Rossum1952e382001-09-19 01:25:16 +0000687 else if (PyFloat_Check(*pw)) {
688 Py_INCREF(*pv);
689 Py_INCREF(*pw);
690 return 0;
691 }
Guido van Rossume6eefc21992-08-14 12:06:52 +0000692 return 1; /* Can't do it */
693}
694
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000695static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +0000696float_long(PyObject *v)
697{
698 double x = PyFloat_AsDouble(v);
699 return PyLong_FromDouble(x);
700}
701
702static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000703float_int(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000704{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000705 double x = PyFloat_AsDouble(v);
Tim Peters7321ec42001-07-26 20:02:17 +0000706 double wholepart; /* integral portion of x, rounded toward 0 */
Tim Peters7321ec42001-07-26 20:02:17 +0000707
708 (void)modf(x, &wholepart);
Tim Peters7d791242002-11-21 22:26:37 +0000709 /* Try to get out cheap if this fits in a Python int. The attempt
710 * to cast to long must be protected, as C doesn't define what
711 * happens if the double is too big to fit in a long. Some rare
712 * systems raise an exception then (RISCOS was mentioned as one,
713 * and someone using a non-default option on Sun also bumped into
714 * that). Note that checking for >= and <= LONG_{MIN,MAX} would
715 * still be vulnerable: if a long has more bits of precision than
716 * a double, casting MIN/MAX to double may yield an approximation,
717 * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
718 * yield true from the C expression wholepart<=LONG_MAX, despite
719 * that wholepart is actually greater than LONG_MAX.
720 */
721 if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
722 const long aslong = (long)wholepart;
Tim Peters7321ec42001-07-26 20:02:17 +0000723 return PyInt_FromLong(aslong);
Tim Peters7d791242002-11-21 22:26:37 +0000724 }
725 return PyLong_FromDouble(wholepart);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000726}
727
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000728static PyObject *
Fred Drakefd99de62000-07-09 05:02:18 +0000729float_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000730{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000731 Py_INCREF(v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +0000732 return v;
733}
734
735
Jeremy Hylton938ace62002-07-17 16:30:39 +0000736static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +0000737float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
738
Tim Peters6d6c1a32001-08-02 04:15:00 +0000739static PyObject *
740float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
741{
742 PyObject *x = Py_False; /* Integer zero */
743 static char *kwlist[] = {"x", 0};
744
Guido van Rossumbef14172001-08-29 15:47:46 +0000745 if (type != &PyFloat_Type)
746 return float_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000747 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
748 return NULL;
749 if (PyString_Check(x))
750 return PyFloat_FromString(x, NULL);
751 return PyNumber_Float(x);
752}
753
Guido van Rossumbef14172001-08-29 15:47:46 +0000754/* Wimpy, slow approach to tp_new calls for subtypes of float:
755 first create a regular float from whatever arguments we got,
756 then allocate a subtype instance and initialize its ob_fval
757 from the regular float. The regular float is then thrown away.
758*/
759static PyObject *
760float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
761{
762 PyObject *tmp, *new;
763
764 assert(PyType_IsSubtype(type, &PyFloat_Type));
765 tmp = float_new(&PyFloat_Type, args, kwds);
766 if (tmp == NULL)
767 return NULL;
Tim Peters2400fa42001-09-12 19:12:49 +0000768 assert(PyFloat_CheckExact(tmp));
Guido van Rossumd93dce12001-08-30 03:09:31 +0000769 new = type->tp_alloc(type, 0);
Raymond Hettingerf4667932003-06-28 20:04:25 +0000770 if (new == NULL) {
771 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +0000772 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +0000773 }
Guido van Rossumbef14172001-08-29 15:47:46 +0000774 ((PyFloatObject *)new)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
775 Py_DECREF(tmp);
776 return new;
777}
778
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000779static PyObject *
780float_getnewargs(PyFloatObject *v)
781{
782 return Py_BuildValue("(d)", v->ob_fval);
783}
784
785static PyMethodDef float_methods[] = {
786 {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
787 {NULL, NULL} /* sentinel */
788};
789
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000790PyDoc_STRVAR(float_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000791"float(x) -> floating point number\n\
792\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000793Convert a string or number to a floating point number, if possible.");
Tim Peters6d6c1a32001-08-02 04:15:00 +0000794
795
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000796static PyNumberMethods float_as_number = {
Guido van Rossumb6775db1994-08-01 11:34:53 +0000797 (binaryfunc)float_add, /*nb_add*/
798 (binaryfunc)float_sub, /*nb_subtract*/
799 (binaryfunc)float_mul, /*nb_multiply*/
Guido van Rossum393661d2001-08-31 17:40:15 +0000800 (binaryfunc)float_classic_div, /*nb_divide*/
Guido van Rossumb6775db1994-08-01 11:34:53 +0000801 (binaryfunc)float_rem, /*nb_remainder*/
802 (binaryfunc)float_divmod, /*nb_divmod*/
Guido van Rossum0b7d02a1994-08-12 12:52:35 +0000803 (ternaryfunc)float_pow, /*nb_power*/
Guido van Rossumb6775db1994-08-01 11:34:53 +0000804 (unaryfunc)float_neg, /*nb_negative*/
805 (unaryfunc)float_pos, /*nb_positive*/
806 (unaryfunc)float_abs, /*nb_absolute*/
807 (inquiry)float_nonzero, /*nb_nonzero*/
Guido van Rossum27acb331991-10-24 14:55:28 +0000808 0, /*nb_invert*/
809 0, /*nb_lshift*/
810 0, /*nb_rshift*/
811 0, /*nb_and*/
812 0, /*nb_xor*/
813 0, /*nb_or*/
Guido van Rossumb6775db1994-08-01 11:34:53 +0000814 (coercion)float_coerce, /*nb_coerce*/
815 (unaryfunc)float_int, /*nb_int*/
816 (unaryfunc)float_long, /*nb_long*/
817 (unaryfunc)float_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +0000818 0, /* nb_oct */
819 0, /* nb_hex */
820 0, /* nb_inplace_add */
821 0, /* nb_inplace_subtract */
822 0, /* nb_inplace_multiply */
823 0, /* nb_inplace_divide */
824 0, /* nb_inplace_remainder */
825 0, /* nb_inplace_power */
826 0, /* nb_inplace_lshift */
827 0, /* nb_inplace_rshift */
828 0, /* nb_inplace_and */
829 0, /* nb_inplace_xor */
830 0, /* nb_inplace_or */
Tim Peters63a35712001-12-11 19:57:24 +0000831 float_floor_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +0000832 float_div, /* nb_true_divide */
833 0, /* nb_inplace_floor_divide */
834 0, /* nb_inplace_true_divide */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000835};
836
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000837PyTypeObject PyFloat_Type = {
838 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000839 0,
840 "float",
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000841 sizeof(PyFloatObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000842 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +0000843 (destructor)float_dealloc, /* tp_dealloc */
844 (printfunc)float_print, /* tp_print */
845 0, /* tp_getattr */
846 0, /* tp_setattr */
Michael W. Hudson08678a12004-05-26 17:36:12 +0000847 0, /* tp_compare */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000848 (reprfunc)float_repr, /* tp_repr */
849 &float_as_number, /* tp_as_number */
850 0, /* tp_as_sequence */
851 0, /* tp_as_mapping */
852 (hashfunc)float_hash, /* tp_hash */
853 0, /* tp_call */
854 (reprfunc)float_str, /* tp_str */
855 PyObject_GenericGetAttr, /* tp_getattro */
856 0, /* tp_setattro */
857 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +0000858 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
859 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000860 float_doc, /* tp_doc */
861 0, /* tp_traverse */
862 0, /* tp_clear */
Michael W. Hudsond3b33b52004-02-19 19:35:22 +0000863 (richcmpfunc)float_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000864 0, /* tp_weaklistoffset */
865 0, /* tp_iter */
866 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +0000867 float_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +0000868 0, /* tp_members */
869 0, /* tp_getset */
870 0, /* tp_base */
871 0, /* tp_dict */
872 0, /* tp_descr_get */
873 0, /* tp_descr_set */
874 0, /* tp_dictoffset */
875 0, /* tp_init */
876 0, /* tp_alloc */
877 float_new, /* tp_new */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000878};
Guido van Rossumfbbd57e1997-08-05 02:16:08 +0000879
880void
Fred Drakefd99de62000-07-09 05:02:18 +0000881PyFloat_Fini(void)
Guido van Rossumfbbd57e1997-08-05 02:16:08 +0000882{
Guido van Rossum3fce8831999-03-12 19:43:17 +0000883 PyFloatObject *p;
884 PyFloatBlock *list, *next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000885 int i;
886 int bc, bf; /* block count, number of freed blocks */
887 int frem, fsum; /* remaining unfreed floats per block, total */
888
889 bc = 0;
890 bf = 0;
891 fsum = 0;
892 list = block_list;
893 block_list = NULL;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +0000894 free_list = NULL;
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000895 while (list != NULL) {
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000896 bc++;
897 frem = 0;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +0000898 for (i = 0, p = &list->objects[0];
899 i < N_FLOATOBJECTS;
900 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +0000901 if (PyFloat_CheckExact(p) && p->ob_refcnt != 0)
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000902 frem++;
903 }
Guido van Rossum3fce8831999-03-12 19:43:17 +0000904 next = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000905 if (frem) {
Guido van Rossum3fce8831999-03-12 19:43:17 +0000906 list->next = block_list;
907 block_list = list;
Guido van Rossumd7b5fb81999-03-19 20:59:40 +0000908 for (i = 0, p = &list->objects[0];
909 i < N_FLOATOBJECTS;
910 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +0000911 if (!PyFloat_CheckExact(p) ||
Guido van Rossumbef14172001-08-29 15:47:46 +0000912 p->ob_refcnt == 0) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +0000913 p->ob_type = (struct _typeobject *)
914 free_list;
915 free_list = p;
916 }
917 }
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000918 }
919 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000920 PyMem_FREE(list); /* XXX PyObject_FREE ??? */
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000921 bf++;
922 }
923 fsum += frem;
Guido van Rossum3fce8831999-03-12 19:43:17 +0000924 list = next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000925 }
Guido van Rossum3fce8831999-03-12 19:43:17 +0000926 if (!Py_VerboseFlag)
927 return;
928 fprintf(stderr, "# cleanup floats");
929 if (!fsum) {
930 fprintf(stderr, "\n");
931 }
932 else {
933 fprintf(stderr,
934 ": %d unfreed float%s in %d out of %d block%s\n",
935 fsum, fsum == 1 ? "" : "s",
936 bc - bf, bc, bc == 1 ? "" : "s");
937 }
938 if (Py_VerboseFlag > 1) {
939 list = block_list;
940 while (list != NULL) {
Guido van Rossumd7b5fb81999-03-19 20:59:40 +0000941 for (i = 0, p = &list->objects[0];
942 i < N_FLOATOBJECTS;
943 i++, p++) {
Guido van Rossumdea6ef92001-09-11 16:13:52 +0000944 if (PyFloat_CheckExact(p) &&
Guido van Rossumbef14172001-08-29 15:47:46 +0000945 p->ob_refcnt != 0) {
Guido van Rossum3fce8831999-03-12 19:43:17 +0000946 char buf[100];
947 PyFloat_AsString(buf, p);
948 fprintf(stderr,
Fred Drakea44d3532000-06-30 15:01:00 +0000949 "# <float at %p, refcnt=%d, val=%s>\n",
950 p, p->ob_refcnt, buf);
Guido van Rossum3fce8831999-03-12 19:43:17 +0000951 }
952 }
953 list = list->next;
Guido van Rossumf61bbc81999-03-12 00:12:21 +0000954 }
955 }
Guido van Rossumfbbd57e1997-08-05 02:16:08 +0000956}
Tim Peters9905b942003-03-20 20:53:32 +0000957
958/*----------------------------------------------------------------------------
959 * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.
960 *
961 * TODO: On platforms that use the standard IEEE-754 single and double
962 * formats natively, these routines could simply copy the bytes.
963 */
964int
965_PyFloat_Pack4(double x, unsigned char *p, int le)
966{
967 unsigned char sign;
968 int e;
969 double f;
970 unsigned int fbits;
971 int incr = 1;
972
973 if (le) {
974 p += 3;
975 incr = -1;
976 }
977
978 if (x < 0) {
979 sign = 1;
980 x = -x;
981 }
982 else
983 sign = 0;
984
985 f = frexp(x, &e);
986
987 /* Normalize f to be in the range [1.0, 2.0) */
988 if (0.5 <= f && f < 1.0) {
989 f *= 2.0;
990 e--;
991 }
992 else if (f == 0.0)
993 e = 0;
994 else {
995 PyErr_SetString(PyExc_SystemError,
996 "frexp() result out of range");
997 return -1;
998 }
999
1000 if (e >= 128)
1001 goto Overflow;
1002 else if (e < -126) {
1003 /* Gradual underflow */
1004 f = ldexp(f, 126 + e);
1005 e = 0;
1006 }
1007 else if (!(e == 0 && f == 0.0)) {
1008 e += 127;
1009 f -= 1.0; /* Get rid of leading 1 */
1010 }
1011
1012 f *= 8388608.0; /* 2**23 */
Tim Petersf1ed9342003-03-21 17:10:03 +00001013 fbits = (unsigned int)(f + 0.5); /* Round */
Tim Peters9905b942003-03-20 20:53:32 +00001014 assert(fbits <= 8388608);
1015 if (fbits >> 23) {
1016 /* The carry propagated out of a string of 23 1 bits. */
1017 fbits = 0;
1018 ++e;
1019 if (e >= 255)
1020 goto Overflow;
1021 }
1022
1023 /* First byte */
1024 *p = (sign << 7) | (e >> 1);
1025 p += incr;
1026
1027 /* Second byte */
1028 *p = (char) (((e & 1) << 7) | (fbits >> 16));
1029 p += incr;
1030
1031 /* Third byte */
1032 *p = (fbits >> 8) & 0xFF;
1033 p += incr;
1034
1035 /* Fourth byte */
1036 *p = fbits & 0xFF;
1037
1038 /* Done */
1039 return 0;
1040
1041 Overflow:
1042 PyErr_SetString(PyExc_OverflowError,
1043 "float too large to pack with f format");
1044 return -1;
1045}
1046
1047int
1048_PyFloat_Pack8(double x, unsigned char *p, int le)
1049{
1050 unsigned char sign;
1051 int e;
1052 double f;
1053 unsigned int fhi, flo;
1054 int incr = 1;
1055
1056 if (le) {
1057 p += 7;
1058 incr = -1;
1059 }
1060
1061 if (x < 0) {
1062 sign = 1;
1063 x = -x;
1064 }
1065 else
1066 sign = 0;
1067
1068 f = frexp(x, &e);
1069
1070 /* Normalize f to be in the range [1.0, 2.0) */
1071 if (0.5 <= f && f < 1.0) {
1072 f *= 2.0;
1073 e--;
1074 }
1075 else if (f == 0.0)
1076 e = 0;
1077 else {
1078 PyErr_SetString(PyExc_SystemError,
1079 "frexp() result out of range");
1080 return -1;
1081 }
1082
1083 if (e >= 1024)
1084 goto Overflow;
1085 else if (e < -1022) {
1086 /* Gradual underflow */
1087 f = ldexp(f, 1022 + e);
1088 e = 0;
1089 }
1090 else if (!(e == 0 && f == 0.0)) {
1091 e += 1023;
1092 f -= 1.0; /* Get rid of leading 1 */
1093 }
1094
1095 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1096 f *= 268435456.0; /* 2**28 */
1097 fhi = (unsigned int)f; /* Truncate */
1098 assert(fhi < 268435456);
1099
1100 f -= (double)fhi;
1101 f *= 16777216.0; /* 2**24 */
1102 flo = (unsigned int)(f + 0.5); /* Round */
1103 assert(flo <= 16777216);
1104 if (flo >> 24) {
1105 /* The carry propagated out of a string of 24 1 bits. */
1106 flo = 0;
1107 ++fhi;
1108 if (fhi >> 28) {
1109 /* And it also progagated out of the next 28 bits. */
1110 fhi = 0;
1111 ++e;
1112 if (e >= 2047)
1113 goto Overflow;
1114 }
1115 }
1116
1117 /* First byte */
1118 *p = (sign << 7) | (e >> 4);
1119 p += incr;
1120
1121 /* Second byte */
1122 *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
1123 p += incr;
1124
1125 /* Third byte */
1126 *p = (fhi >> 16) & 0xFF;
1127 p += incr;
1128
1129 /* Fourth byte */
1130 *p = (fhi >> 8) & 0xFF;
1131 p += incr;
1132
1133 /* Fifth byte */
1134 *p = fhi & 0xFF;
1135 p += incr;
1136
1137 /* Sixth byte */
1138 *p = (flo >> 16) & 0xFF;
1139 p += incr;
1140
1141 /* Seventh byte */
1142 *p = (flo >> 8) & 0xFF;
1143 p += incr;
1144
1145 /* Eighth byte */
1146 *p = flo & 0xFF;
1147 p += incr;
1148
1149 /* Done */
1150 return 0;
1151
1152 Overflow:
1153 PyErr_SetString(PyExc_OverflowError,
1154 "float too large to pack with d format");
1155 return -1;
1156}
1157
1158double
1159_PyFloat_Unpack4(const unsigned char *p, int le)
1160{
1161 unsigned char sign;
1162 int e;
1163 unsigned int f;
1164 double x;
1165 int incr = 1;
1166
1167 if (le) {
1168 p += 3;
1169 incr = -1;
1170 }
1171
1172 /* First byte */
1173 sign = (*p >> 7) & 1;
1174 e = (*p & 0x7F) << 1;
1175 p += incr;
1176
1177 /* Second byte */
1178 e |= (*p >> 7) & 1;
1179 f = (*p & 0x7F) << 16;
1180 p += incr;
1181
1182 /* Third byte */
1183 f |= *p << 8;
1184 p += incr;
1185
1186 /* Fourth byte */
1187 f |= *p;
1188
1189 x = (double)f / 8388608.0;
1190
1191 /* XXX This sadly ignores Inf/NaN issues */
1192 if (e == 0)
1193 e = -126;
1194 else {
1195 x += 1.0;
1196 e -= 127;
1197 }
1198 x = ldexp(x, e);
1199
1200 if (sign)
1201 x = -x;
1202
1203 return x;
1204}
1205
1206double
1207_PyFloat_Unpack8(const unsigned char *p, int le)
1208{
1209 unsigned char sign;
1210 int e;
1211 unsigned int fhi, flo;
1212 double x;
1213 int incr = 1;
1214
1215 if (le) {
1216 p += 7;
1217 incr = -1;
1218 }
1219
1220 /* First byte */
1221 sign = (*p >> 7) & 1;
1222 e = (*p & 0x7F) << 4;
1223 p += incr;
1224
1225 /* Second byte */
1226 e |= (*p >> 4) & 0xF;
1227 fhi = (*p & 0xF) << 24;
1228 p += incr;
1229
1230 /* Third byte */
1231 fhi |= *p << 16;
1232 p += incr;
1233
1234 /* Fourth byte */
1235 fhi |= *p << 8;
1236 p += incr;
1237
1238 /* Fifth byte */
1239 fhi |= *p;
1240 p += incr;
1241
1242 /* Sixth byte */
1243 flo = *p << 16;
1244 p += incr;
1245
1246 /* Seventh byte */
1247 flo |= *p << 8;
1248 p += incr;
1249
1250 /* Eighth byte */
1251 flo |= *p;
1252
1253 x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
1254 x /= 268435456.0; /* 2**28 */
1255
1256 /* XXX This sadly ignores Inf/NaN */
1257 if (e == 0)
1258 e = -1022;
1259 else {
1260 x += 1.0;
1261 e -= 1023;
1262 }
1263 x = ldexp(x, e);
1264
1265 if (sign)
1266 x = -x;
1267
1268 return x;
1269}