]>
Commit | Line | Data |
---|---|---|
53b2ba57 DM |
1 | \r |
2 | /* Float object implementation */\r | |
3 | \r | |
4 | /* XXX There should be overflow checks here, but it's hard to check\r | |
5 | for any kind of float exception without losing portability. */\r | |
6 | \r | |
7 | #include "Python.h"\r | |
8 | #include "structseq.h"\r | |
9 | \r | |
10 | #include <ctype.h>\r | |
11 | #include <float.h>\r | |
12 | \r | |
13 | #undef MAX\r | |
14 | #undef MIN\r | |
15 | #define MAX(x, y) ((x) < (y) ? (y) : (x))\r | |
16 | #define MIN(x, y) ((x) < (y) ? (x) : (y))\r | |
17 | \r | |
18 | #ifdef _OSF_SOURCE\r | |
19 | /* OSF1 5.1 doesn't make this available with XOPEN_SOURCE_EXTENDED defined */\r | |
20 | extern int finite(double);\r | |
21 | #endif\r | |
22 | \r | |
23 | /* Special free list -- see comments for same code in intobject.c. */\r | |
24 | #define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */\r | |
25 | #define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */\r | |
26 | #define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))\r | |
27 | \r | |
28 | struct _floatblock {\r | |
29 | struct _floatblock *next;\r | |
30 | PyFloatObject objects[N_FLOATOBJECTS];\r | |
31 | };\r | |
32 | \r | |
33 | typedef struct _floatblock PyFloatBlock;\r | |
34 | \r | |
35 | static PyFloatBlock *block_list = NULL;\r | |
36 | static PyFloatObject *free_list = NULL;\r | |
37 | \r | |
38 | static PyFloatObject *\r | |
39 | fill_free_list(void)\r | |
40 | {\r | |
41 | PyFloatObject *p, *q;\r | |
42 | /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */\r | |
43 | p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));\r | |
44 | if (p == NULL)\r | |
45 | return (PyFloatObject *) PyErr_NoMemory();\r | |
46 | ((PyFloatBlock *)p)->next = block_list;\r | |
47 | block_list = (PyFloatBlock *)p;\r | |
48 | p = &((PyFloatBlock *)p)->objects[0];\r | |
49 | q = p + N_FLOATOBJECTS;\r | |
50 | while (--q > p)\r | |
51 | Py_TYPE(q) = (struct _typeobject *)(q-1);\r | |
52 | Py_TYPE(q) = NULL;\r | |
53 | return p + N_FLOATOBJECTS - 1;\r | |
54 | }\r | |
55 | \r | |
56 | double\r | |
57 | PyFloat_GetMax(void)\r | |
58 | {\r | |
59 | return DBL_MAX;\r | |
60 | }\r | |
61 | \r | |
62 | double\r | |
63 | PyFloat_GetMin(void)\r | |
64 | {\r | |
65 | return DBL_MIN;\r | |
66 | }\r | |
67 | \r | |
68 | static PyTypeObject FloatInfoType = {0, 0, 0, 0, 0, 0};\r | |
69 | \r | |
70 | PyDoc_STRVAR(floatinfo__doc__,\r | |
71 | "sys.float_info\n\\r | |
72 | \n\\r | |
73 | A structseq holding information about the float type. It contains low level\n\\r | |
74 | information about the precision and internal representation. Please study\n\\r | |
75 | your system's :file:`float.h` for more information.");\r | |
76 | \r | |
77 | static PyStructSequence_Field floatinfo_fields[] = {\r | |
78 | {"max", "DBL_MAX -- maximum representable finite float"},\r | |
79 | {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "\r | |
80 | "is representable"},\r | |
81 | {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "\r | |
82 | "is representable"},\r | |
83 | {"min", "DBL_MIN -- Minimum positive normalizer float"},\r | |
84 | {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "\r | |
85 | "is a normalized float"},\r | |
86 | {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "\r | |
87 | "a normalized"},\r | |
88 | {"dig", "DBL_DIG -- digits"},\r | |
89 | {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},\r | |
90 | {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "\r | |
91 | "representable float"},\r | |
92 | {"radix", "FLT_RADIX -- radix of exponent"},\r | |
93 | {"rounds", "FLT_ROUNDS -- addition rounds"},\r | |
94 | {0}\r | |
95 | };\r | |
96 | \r | |
97 | static PyStructSequence_Desc floatinfo_desc = {\r | |
98 | "sys.float_info", /* name */\r | |
99 | floatinfo__doc__, /* doc */\r | |
100 | floatinfo_fields, /* fields */\r | |
101 | 11\r | |
102 | };\r | |
103 | \r | |
104 | PyObject *\r | |
105 | PyFloat_GetInfo(void)\r | |
106 | {\r | |
107 | PyObject* floatinfo;\r | |
108 | int pos = 0;\r | |
109 | \r | |
110 | floatinfo = PyStructSequence_New(&FloatInfoType);\r | |
111 | if (floatinfo == NULL) {\r | |
112 | return NULL;\r | |
113 | }\r | |
114 | \r | |
115 | #define SetIntFlag(flag) \\r | |
116 | PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))\r | |
117 | #define SetDblFlag(flag) \\r | |
118 | PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))\r | |
119 | \r | |
120 | SetDblFlag(DBL_MAX);\r | |
121 | SetIntFlag(DBL_MAX_EXP);\r | |
122 | SetIntFlag(DBL_MAX_10_EXP);\r | |
123 | SetDblFlag(DBL_MIN);\r | |
124 | SetIntFlag(DBL_MIN_EXP);\r | |
125 | SetIntFlag(DBL_MIN_10_EXP);\r | |
126 | SetIntFlag(DBL_DIG);\r | |
127 | SetIntFlag(DBL_MANT_DIG);\r | |
128 | SetDblFlag(DBL_EPSILON);\r | |
129 | SetIntFlag(FLT_RADIX);\r | |
130 | SetIntFlag(FLT_ROUNDS);\r | |
131 | #undef SetIntFlag\r | |
132 | #undef SetDblFlag\r | |
133 | \r | |
134 | if (PyErr_Occurred()) {\r | |
135 | Py_CLEAR(floatinfo);\r | |
136 | return NULL;\r | |
137 | }\r | |
138 | return floatinfo;\r | |
139 | }\r | |
140 | \r | |
141 | PyObject *\r | |
142 | PyFloat_FromDouble(double fval)\r | |
143 | {\r | |
144 | register PyFloatObject *op;\r | |
145 | if (free_list == NULL) {\r | |
146 | if ((free_list = fill_free_list()) == NULL)\r | |
147 | return NULL;\r | |
148 | }\r | |
149 | /* Inline PyObject_New */\r | |
150 | op = free_list;\r | |
151 | free_list = (PyFloatObject *)Py_TYPE(op);\r | |
152 | PyObject_INIT(op, &PyFloat_Type);\r | |
153 | op->ob_fval = fval;\r | |
154 | return (PyObject *) op;\r | |
155 | }\r | |
156 | \r | |
157 | /**************************************************************************\r | |
158 | RED_FLAG 22-Sep-2000 tim\r | |
159 | PyFloat_FromString's pend argument is braindead. Prior to this RED_FLAG,\r | |
160 | \r | |
161 | 1. If v was a regular string, *pend was set to point to its terminating\r | |
162 | null byte. That's useless (the caller can find that without any\r | |
163 | help from this function!).\r | |
164 | \r | |
165 | 2. If v was a Unicode string, or an object convertible to a character\r | |
166 | buffer, *pend was set to point into stack trash (the auto temp\r | |
167 | vector holding the character buffer). That was downright dangerous.\r | |
168 | \r | |
169 | Since we can't change the interface of a public API function, pend is\r | |
170 | still supported but now *officially* useless: if pend is not NULL,\r | |
171 | *pend is set to NULL.\r | |
172 | **************************************************************************/\r | |
173 | PyObject *\r | |
174 | PyFloat_FromString(PyObject *v, char **pend)\r | |
175 | {\r | |
176 | const char *s, *last, *end;\r | |
177 | double x;\r | |
178 | char buffer[256]; /* for errors */\r | |
179 | #ifdef Py_USING_UNICODE\r | |
180 | char *s_buffer = NULL;\r | |
181 | #endif\r | |
182 | Py_ssize_t len;\r | |
183 | PyObject *result = NULL;\r | |
184 | \r | |
185 | if (pend)\r | |
186 | *pend = NULL;\r | |
187 | if (PyString_Check(v)) {\r | |
188 | s = PyString_AS_STRING(v);\r | |
189 | len = PyString_GET_SIZE(v);\r | |
190 | }\r | |
191 | #ifdef Py_USING_UNICODE\r | |
192 | else if (PyUnicode_Check(v)) {\r | |
193 | s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);\r | |
194 | if (s_buffer == NULL)\r | |
195 | return PyErr_NoMemory();\r | |
196 | if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),\r | |
197 | PyUnicode_GET_SIZE(v),\r | |
198 | s_buffer,\r | |
199 | NULL))\r | |
200 | goto error;\r | |
201 | s = s_buffer;\r | |
202 | len = strlen(s);\r | |
203 | }\r | |
204 | #endif\r | |
205 | else if (PyObject_AsCharBuffer(v, &s, &len)) {\r | |
206 | PyErr_SetString(PyExc_TypeError,\r | |
207 | "float() argument must be a string or a number");\r | |
208 | return NULL;\r | |
209 | }\r | |
210 | last = s + len;\r | |
211 | \r | |
212 | while (Py_ISSPACE(*s))\r | |
213 | s++;\r | |
214 | /* We don't care about overflow or underflow. If the platform\r | |
215 | * supports them, infinities and signed zeroes (on underflow) are\r | |
216 | * fine. */\r | |
217 | x = PyOS_string_to_double(s, (char **)&end, NULL);\r | |
218 | if (x == -1.0 && PyErr_Occurred())\r | |
219 | goto error;\r | |
220 | while (Py_ISSPACE(*end))\r | |
221 | end++;\r | |
222 | if (end == last)\r | |
223 | result = PyFloat_FromDouble(x);\r | |
224 | else {\r | |
225 | PyOS_snprintf(buffer, sizeof(buffer),\r | |
226 | "invalid literal for float(): %.200s", s);\r | |
227 | PyErr_SetString(PyExc_ValueError, buffer);\r | |
228 | result = NULL;\r | |
229 | }\r | |
230 | \r | |
231 | error:\r | |
232 | #ifdef Py_USING_UNICODE\r | |
233 | if (s_buffer)\r | |
234 | PyMem_FREE(s_buffer);\r | |
235 | #endif\r | |
236 | return result;\r | |
237 | }\r | |
238 | \r | |
239 | static void\r | |
240 | float_dealloc(PyFloatObject *op)\r | |
241 | {\r | |
242 | if (PyFloat_CheckExact(op)) {\r | |
243 | Py_TYPE(op) = (struct _typeobject *)free_list;\r | |
244 | free_list = op;\r | |
245 | }\r | |
246 | else\r | |
247 | Py_TYPE(op)->tp_free((PyObject *)op);\r | |
248 | }\r | |
249 | \r | |
250 | double\r | |
251 | PyFloat_AsDouble(PyObject *op)\r | |
252 | {\r | |
253 | PyNumberMethods *nb;\r | |
254 | PyFloatObject *fo;\r | |
255 | double val;\r | |
256 | \r | |
257 | if (op && PyFloat_Check(op))\r | |
258 | return PyFloat_AS_DOUBLE((PyFloatObject*) op);\r | |
259 | \r | |
260 | if (op == NULL) {\r | |
261 | PyErr_BadArgument();\r | |
262 | return -1;\r | |
263 | }\r | |
264 | \r | |
265 | if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {\r | |
266 | PyErr_SetString(PyExc_TypeError, "a float is required");\r | |
267 | return -1;\r | |
268 | }\r | |
269 | \r | |
270 | fo = (PyFloatObject*) (*nb->nb_float) (op);\r | |
271 | if (fo == NULL)\r | |
272 | return -1;\r | |
273 | if (!PyFloat_Check(fo)) {\r | |
274 | Py_DECREF(fo);\r | |
275 | PyErr_SetString(PyExc_TypeError,\r | |
276 | "nb_float should return float object");\r | |
277 | return -1;\r | |
278 | }\r | |
279 | \r | |
280 | val = PyFloat_AS_DOUBLE(fo);\r | |
281 | Py_DECREF(fo);\r | |
282 | \r | |
283 | return val;\r | |
284 | }\r | |
285 | \r | |
286 | /* Methods */\r | |
287 | \r | |
288 | /* Macro and helper that convert PyObject obj to a C double and store\r | |
289 | the value in dbl; this replaces the functionality of the coercion\r | |
290 | slot function. If conversion to double raises an exception, obj is\r | |
291 | set to NULL, and the function invoking this macro returns NULL. If\r | |
292 | obj is not of float, int or long type, Py_NotImplemented is incref'ed,\r | |
293 | stored in obj, and returned from the function invoking this macro.\r | |
294 | */\r | |
295 | #define CONVERT_TO_DOUBLE(obj, dbl) \\r | |
296 | if (PyFloat_Check(obj)) \\r | |
297 | dbl = PyFloat_AS_DOUBLE(obj); \\r | |
298 | else if (convert_to_double(&(obj), &(dbl)) < 0) \\r | |
299 | return obj;\r | |
300 | \r | |
301 | static int\r | |
302 | convert_to_double(PyObject **v, double *dbl)\r | |
303 | {\r | |
304 | register PyObject *obj = *v;\r | |
305 | \r | |
306 | if (PyInt_Check(obj)) {\r | |
307 | *dbl = (double)PyInt_AS_LONG(obj);\r | |
308 | }\r | |
309 | else if (PyLong_Check(obj)) {\r | |
310 | *dbl = PyLong_AsDouble(obj);\r | |
311 | if (*dbl == -1.0 && PyErr_Occurred()) {\r | |
312 | *v = NULL;\r | |
313 | return -1;\r | |
314 | }\r | |
315 | }\r | |
316 | else {\r | |
317 | Py_INCREF(Py_NotImplemented);\r | |
318 | *v = Py_NotImplemented;\r | |
319 | return -1;\r | |
320 | }\r | |
321 | return 0;\r | |
322 | }\r | |
323 | \r | |
324 | /* XXX PyFloat_AsString and PyFloat_AsReprString are deprecated:\r | |
325 | XXX they pass a char buffer without passing a length.\r | |
326 | */\r | |
327 | void\r | |
328 | PyFloat_AsString(char *buf, PyFloatObject *v)\r | |
329 | {\r | |
330 | char *tmp = PyOS_double_to_string(v->ob_fval, 'g',\r | |
331 | PyFloat_STR_PRECISION,\r | |
332 | Py_DTSF_ADD_DOT_0, NULL);\r | |
333 | strcpy(buf, tmp);\r | |
334 | PyMem_Free(tmp);\r | |
335 | }\r | |
336 | \r | |
337 | void\r | |
338 | PyFloat_AsReprString(char *buf, PyFloatObject *v)\r | |
339 | {\r | |
340 | char * tmp = PyOS_double_to_string(v->ob_fval, 'r', 0,\r | |
341 | Py_DTSF_ADD_DOT_0, NULL);\r | |
342 | strcpy(buf, tmp);\r | |
343 | PyMem_Free(tmp);\r | |
344 | }\r | |
345 | \r | |
346 | /* ARGSUSED */\r | |
347 | static int\r | |
348 | float_print(PyFloatObject *v, FILE *fp, int flags)\r | |
349 | {\r | |
350 | char *buf;\r | |
351 | if (flags & Py_PRINT_RAW)\r | |
352 | buf = PyOS_double_to_string(v->ob_fval,\r | |
353 | 'g', PyFloat_STR_PRECISION,\r | |
354 | Py_DTSF_ADD_DOT_0, NULL);\r | |
355 | else\r | |
356 | buf = PyOS_double_to_string(v->ob_fval,\r | |
357 | 'r', 0, Py_DTSF_ADD_DOT_0, NULL);\r | |
358 | Py_BEGIN_ALLOW_THREADS\r | |
359 | fputs(buf, fp);\r | |
360 | Py_END_ALLOW_THREADS\r | |
361 | PyMem_Free(buf);\r | |
362 | return 0;\r | |
363 | }\r | |
364 | \r | |
365 | static PyObject *\r | |
366 | float_str_or_repr(PyFloatObject *v, int precision, char format_code)\r | |
367 | {\r | |
368 | PyObject *result;\r | |
369 | char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),\r | |
370 | format_code, precision,\r | |
371 | Py_DTSF_ADD_DOT_0,\r | |
372 | NULL);\r | |
373 | if (!buf)\r | |
374 | return PyErr_NoMemory();\r | |
375 | result = PyString_FromString(buf);\r | |
376 | PyMem_Free(buf);\r | |
377 | return result;\r | |
378 | }\r | |
379 | \r | |
380 | static PyObject *\r | |
381 | float_repr(PyFloatObject *v)\r | |
382 | {\r | |
383 | return float_str_or_repr(v, 0, 'r');\r | |
384 | }\r | |
385 | \r | |
386 | static PyObject *\r | |
387 | float_str(PyFloatObject *v)\r | |
388 | {\r | |
389 | return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');\r | |
390 | }\r | |
391 | \r | |
392 | /* Comparison is pretty much a nightmare. When comparing float to float,\r | |
393 | * we do it as straightforwardly (and long-windedly) as conceivable, so\r | |
394 | * that, e.g., Python x == y delivers the same result as the platform\r | |
395 | * C x == y when x and/or y is a NaN.\r | |
396 | * When mixing float with an integer type, there's no good *uniform* approach.\r | |
397 | * Converting the double to an integer obviously doesn't work, since we\r | |
398 | * may lose info from fractional bits. Converting the integer to a double\r | |
399 | * also has two failure modes: (1) a long int may trigger overflow (too\r | |
400 | * large to fit in the dynamic range of a C double); (2) even a C long may have\r | |
401 | * more bits than fit in a C double (e.g., on a a 64-bit box long may have\r | |
402 | * 63 bits of precision, but a C double probably has only 53), and then\r | |
403 | * we can falsely claim equality when low-order integer bits are lost by\r | |
404 | * coercion to double. So this part is painful too.\r | |
405 | */\r | |
406 | \r | |
407 | static PyObject*\r | |
408 | float_richcompare(PyObject *v, PyObject *w, int op)\r | |
409 | {\r | |
410 | double i, j;\r | |
411 | int r = 0;\r | |
412 | \r | |
413 | assert(PyFloat_Check(v));\r | |
414 | i = PyFloat_AS_DOUBLE(v);\r | |
415 | \r | |
416 | /* Switch on the type of w. Set i and j to doubles to be compared,\r | |
417 | * and op to the richcomp to use.\r | |
418 | */\r | |
419 | if (PyFloat_Check(w))\r | |
420 | j = PyFloat_AS_DOUBLE(w);\r | |
421 | \r | |
422 | else if (!Py_IS_FINITE(i)) {\r | |
423 | if (PyInt_Check(w) || PyLong_Check(w))\r | |
424 | /* If i is an infinity, its magnitude exceeds any\r | |
425 | * finite integer, so it doesn't matter which int we\r | |
426 | * compare i with. If i is a NaN, similarly.\r | |
427 | */\r | |
428 | j = 0.0;\r | |
429 | else\r | |
430 | goto Unimplemented;\r | |
431 | }\r | |
432 | \r | |
433 | else if (PyInt_Check(w)) {\r | |
434 | long jj = PyInt_AS_LONG(w);\r | |
435 | /* In the worst realistic case I can imagine, C double is a\r | |
436 | * Cray single with 48 bits of precision, and long has 64\r | |
437 | * bits.\r | |
438 | */\r | |
439 | #if SIZEOF_LONG > 6\r | |
440 | unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);\r | |
441 | if (abs >> 48) {\r | |
442 | /* Needs more than 48 bits. Make it take the\r | |
443 | * PyLong path.\r | |
444 | */\r | |
445 | PyObject *result;\r | |
446 | PyObject *ww = PyLong_FromLong(jj);\r | |
447 | \r | |
448 | if (ww == NULL)\r | |
449 | return NULL;\r | |
450 | result = float_richcompare(v, ww, op);\r | |
451 | Py_DECREF(ww);\r | |
452 | return result;\r | |
453 | }\r | |
454 | #endif\r | |
455 | j = (double)jj;\r | |
456 | assert((long)j == jj);\r | |
457 | }\r | |
458 | \r | |
459 | else if (PyLong_Check(w)) {\r | |
460 | int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;\r | |
461 | int wsign = _PyLong_Sign(w);\r | |
462 | size_t nbits;\r | |
463 | int exponent;\r | |
464 | \r | |
465 | if (vsign != wsign) {\r | |
466 | /* Magnitudes are irrelevant -- the signs alone\r | |
467 | * determine the outcome.\r | |
468 | */\r | |
469 | i = (double)vsign;\r | |
470 | j = (double)wsign;\r | |
471 | goto Compare;\r | |
472 | }\r | |
473 | /* The signs are the same. */\r | |
474 | /* Convert w to a double if it fits. In particular, 0 fits. */\r | |
475 | nbits = _PyLong_NumBits(w);\r | |
476 | if (nbits == (size_t)-1 && PyErr_Occurred()) {\r | |
477 | /* This long is so large that size_t isn't big enough\r | |
478 | * to hold the # of bits. Replace with little doubles\r | |
479 | * that give the same outcome -- w is so large that\r | |
480 | * its magnitude must exceed the magnitude of any\r | |
481 | * finite float.\r | |
482 | */\r | |
483 | PyErr_Clear();\r | |
484 | i = (double)vsign;\r | |
485 | assert(wsign != 0);\r | |
486 | j = wsign * 2.0;\r | |
487 | goto Compare;\r | |
488 | }\r | |
489 | if (nbits <= 48) {\r | |
490 | j = PyLong_AsDouble(w);\r | |
491 | /* It's impossible that <= 48 bits overflowed. */\r | |
492 | assert(j != -1.0 || ! PyErr_Occurred());\r | |
493 | goto Compare;\r | |
494 | }\r | |
495 | assert(wsign != 0); /* else nbits was 0 */\r | |
496 | assert(vsign != 0); /* if vsign were 0, then since wsign is\r | |
497 | * not 0, we would have taken the\r | |
498 | * vsign != wsign branch at the start */\r | |
499 | /* We want to work with non-negative numbers. */\r | |
500 | if (vsign < 0) {\r | |
501 | /* "Multiply both sides" by -1; this also swaps the\r | |
502 | * comparator.\r | |
503 | */\r | |
504 | i = -i;\r | |
505 | op = _Py_SwappedOp[op];\r | |
506 | }\r | |
507 | assert(i > 0.0);\r | |
508 | (void) frexp(i, &exponent);\r | |
509 | /* exponent is the # of bits in v before the radix point;\r | |
510 | * we know that nbits (the # of bits in w) > 48 at this point\r | |
511 | */\r | |
512 | if (exponent < 0 || (size_t)exponent < nbits) {\r | |
513 | i = 1.0;\r | |
514 | j = 2.0;\r | |
515 | goto Compare;\r | |
516 | }\r | |
517 | if ((size_t)exponent > nbits) {\r | |
518 | i = 2.0;\r | |
519 | j = 1.0;\r | |
520 | goto Compare;\r | |
521 | }\r | |
522 | /* v and w have the same number of bits before the radix\r | |
523 | * point. Construct two longs that have the same comparison\r | |
524 | * outcome.\r | |
525 | */\r | |
526 | {\r | |
527 | double fracpart;\r | |
528 | double intpart;\r | |
529 | PyObject *result = NULL;\r | |
530 | PyObject *one = NULL;\r | |
531 | PyObject *vv = NULL;\r | |
532 | PyObject *ww = w;\r | |
533 | \r | |
534 | if (wsign < 0) {\r | |
535 | ww = PyNumber_Negative(w);\r | |
536 | if (ww == NULL)\r | |
537 | goto Error;\r | |
538 | }\r | |
539 | else\r | |
540 | Py_INCREF(ww);\r | |
541 | \r | |
542 | fracpart = modf(i, &intpart);\r | |
543 | vv = PyLong_FromDouble(intpart);\r | |
544 | if (vv == NULL)\r | |
545 | goto Error;\r | |
546 | \r | |
547 | if (fracpart != 0.0) {\r | |
548 | /* Shift left, and or a 1 bit into vv\r | |
549 | * to represent the lost fraction.\r | |
550 | */\r | |
551 | PyObject *temp;\r | |
552 | \r | |
553 | one = PyInt_FromLong(1);\r | |
554 | if (one == NULL)\r | |
555 | goto Error;\r | |
556 | \r | |
557 | temp = PyNumber_Lshift(ww, one);\r | |
558 | if (temp == NULL)\r | |
559 | goto Error;\r | |
560 | Py_DECREF(ww);\r | |
561 | ww = temp;\r | |
562 | \r | |
563 | temp = PyNumber_Lshift(vv, one);\r | |
564 | if (temp == NULL)\r | |
565 | goto Error;\r | |
566 | Py_DECREF(vv);\r | |
567 | vv = temp;\r | |
568 | \r | |
569 | temp = PyNumber_Or(vv, one);\r | |
570 | if (temp == NULL)\r | |
571 | goto Error;\r | |
572 | Py_DECREF(vv);\r | |
573 | vv = temp;\r | |
574 | }\r | |
575 | \r | |
576 | r = PyObject_RichCompareBool(vv, ww, op);\r | |
577 | if (r < 0)\r | |
578 | goto Error;\r | |
579 | result = PyBool_FromLong(r);\r | |
580 | Error:\r | |
581 | Py_XDECREF(vv);\r | |
582 | Py_XDECREF(ww);\r | |
583 | Py_XDECREF(one);\r | |
584 | return result;\r | |
585 | }\r | |
586 | } /* else if (PyLong_Check(w)) */\r | |
587 | \r | |
588 | else /* w isn't float, int, or long */\r | |
589 | goto Unimplemented;\r | |
590 | \r | |
591 | Compare:\r | |
592 | PyFPE_START_PROTECT("richcompare", return NULL)\r | |
593 | switch (op) {\r | |
594 | case Py_EQ:\r | |
595 | r = i == j;\r | |
596 | break;\r | |
597 | case Py_NE:\r | |
598 | r = i != j;\r | |
599 | break;\r | |
600 | case Py_LE:\r | |
601 | r = i <= j;\r | |
602 | break;\r | |
603 | case Py_GE:\r | |
604 | r = i >= j;\r | |
605 | break;\r | |
606 | case Py_LT:\r | |
607 | r = i < j;\r | |
608 | break;\r | |
609 | case Py_GT:\r | |
610 | r = i > j;\r | |
611 | break;\r | |
612 | }\r | |
613 | PyFPE_END_PROTECT(r)\r | |
614 | return PyBool_FromLong(r);\r | |
615 | \r | |
616 | Unimplemented:\r | |
617 | Py_INCREF(Py_NotImplemented);\r | |
618 | return Py_NotImplemented;\r | |
619 | }\r | |
620 | \r | |
621 | static long\r | |
622 | float_hash(PyFloatObject *v)\r | |
623 | {\r | |
624 | return _Py_HashDouble(v->ob_fval);\r | |
625 | }\r | |
626 | \r | |
627 | static PyObject *\r | |
628 | float_add(PyObject *v, PyObject *w)\r | |
629 | {\r | |
630 | double a,b;\r | |
631 | CONVERT_TO_DOUBLE(v, a);\r | |
632 | CONVERT_TO_DOUBLE(w, b);\r | |
633 | PyFPE_START_PROTECT("add", return 0)\r | |
634 | a = a + b;\r | |
635 | PyFPE_END_PROTECT(a)\r | |
636 | return PyFloat_FromDouble(a);\r | |
637 | }\r | |
638 | \r | |
639 | static PyObject *\r | |
640 | float_sub(PyObject *v, PyObject *w)\r | |
641 | {\r | |
642 | double a,b;\r | |
643 | CONVERT_TO_DOUBLE(v, a);\r | |
644 | CONVERT_TO_DOUBLE(w, b);\r | |
645 | PyFPE_START_PROTECT("subtract", return 0)\r | |
646 | a = a - b;\r | |
647 | PyFPE_END_PROTECT(a)\r | |
648 | return PyFloat_FromDouble(a);\r | |
649 | }\r | |
650 | \r | |
651 | static PyObject *\r | |
652 | float_mul(PyObject *v, PyObject *w)\r | |
653 | {\r | |
654 | double a,b;\r | |
655 | CONVERT_TO_DOUBLE(v, a);\r | |
656 | CONVERT_TO_DOUBLE(w, b);\r | |
657 | PyFPE_START_PROTECT("multiply", return 0)\r | |
658 | a = a * b;\r | |
659 | PyFPE_END_PROTECT(a)\r | |
660 | return PyFloat_FromDouble(a);\r | |
661 | }\r | |
662 | \r | |
663 | static PyObject *\r | |
664 | float_div(PyObject *v, PyObject *w)\r | |
665 | {\r | |
666 | double a,b;\r | |
667 | CONVERT_TO_DOUBLE(v, a);\r | |
668 | CONVERT_TO_DOUBLE(w, b);\r | |
669 | #ifdef Py_NAN\r | |
670 | if (b == 0.0) {\r | |
671 | PyErr_SetString(PyExc_ZeroDivisionError,\r | |
672 | "float division by zero");\r | |
673 | return NULL;\r | |
674 | }\r | |
675 | #endif\r | |
676 | PyFPE_START_PROTECT("divide", return 0)\r | |
677 | a = a / b;\r | |
678 | PyFPE_END_PROTECT(a)\r | |
679 | return PyFloat_FromDouble(a);\r | |
680 | }\r | |
681 | \r | |
682 | static PyObject *\r | |
683 | float_classic_div(PyObject *v, PyObject *w)\r | |
684 | {\r | |
685 | double a,b;\r | |
686 | CONVERT_TO_DOUBLE(v, a);\r | |
687 | CONVERT_TO_DOUBLE(w, b);\r | |
688 | if (Py_DivisionWarningFlag >= 2 &&\r | |
689 | PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)\r | |
690 | return NULL;\r | |
691 | #ifdef Py_NAN\r | |
692 | if (b == 0.0) {\r | |
693 | PyErr_SetString(PyExc_ZeroDivisionError,\r | |
694 | "float division by zero");\r | |
695 | return NULL;\r | |
696 | }\r | |
697 | #endif\r | |
698 | PyFPE_START_PROTECT("divide", return 0)\r | |
699 | a = a / b;\r | |
700 | PyFPE_END_PROTECT(a)\r | |
701 | return PyFloat_FromDouble(a);\r | |
702 | }\r | |
703 | \r | |
704 | static PyObject *\r | |
705 | float_rem(PyObject *v, PyObject *w)\r | |
706 | {\r | |
707 | double vx, wx;\r | |
708 | double mod;\r | |
709 | CONVERT_TO_DOUBLE(v, vx);\r | |
710 | CONVERT_TO_DOUBLE(w, wx);\r | |
711 | #ifdef Py_NAN\r | |
712 | if (wx == 0.0) {\r | |
713 | PyErr_SetString(PyExc_ZeroDivisionError,\r | |
714 | "float modulo");\r | |
715 | return NULL;\r | |
716 | }\r | |
717 | #endif\r | |
718 | PyFPE_START_PROTECT("modulo", return 0)\r | |
719 | mod = fmod(vx, wx);\r | |
720 | if (mod) {\r | |
721 | /* ensure the remainder has the same sign as the denominator */\r | |
722 | if ((wx < 0) != (mod < 0)) {\r | |
723 | mod += wx;\r | |
724 | }\r | |
725 | }\r | |
726 | else {\r | |
727 | /* the remainder is zero, and in the presence of signed zeroes\r | |
728 | fmod returns different results across platforms; ensure\r | |
729 | it has the same sign as the denominator; we'd like to do\r | |
730 | "mod = wx * 0.0", but that may get optimized away */\r | |
731 | mod *= mod; /* hide "mod = +0" from optimizer */\r | |
732 | if (wx < 0.0)\r | |
733 | mod = -mod;\r | |
734 | }\r | |
735 | PyFPE_END_PROTECT(mod)\r | |
736 | return PyFloat_FromDouble(mod);\r | |
737 | }\r | |
738 | \r | |
739 | static PyObject *\r | |
740 | float_divmod(PyObject *v, PyObject *w)\r | |
741 | {\r | |
742 | double vx, wx;\r | |
743 | double div, mod, floordiv;\r | |
744 | CONVERT_TO_DOUBLE(v, vx);\r | |
745 | CONVERT_TO_DOUBLE(w, wx);\r | |
746 | if (wx == 0.0) {\r | |
747 | PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");\r | |
748 | return NULL;\r | |
749 | }\r | |
750 | PyFPE_START_PROTECT("divmod", return 0)\r | |
751 | mod = fmod(vx, wx);\r | |
752 | /* fmod is typically exact, so vx-mod is *mathematically* an\r | |
753 | exact multiple of wx. But this is fp arithmetic, and fp\r | |
754 | vx - mod is an approximation; the result is that div may\r | |
755 | not be an exact integral value after the division, although\r | |
756 | it will always be very close to one.\r | |
757 | */\r | |
758 | div = (vx - mod) / wx;\r | |
759 | if (mod) {\r | |
760 | /* ensure the remainder has the same sign as the denominator */\r | |
761 | if ((wx < 0) != (mod < 0)) {\r | |
762 | mod += wx;\r | |
763 | div -= 1.0;\r | |
764 | }\r | |
765 | }\r | |
766 | else {\r | |
767 | /* the remainder is zero, and in the presence of signed zeroes\r | |
768 | fmod returns different results across platforms; ensure\r | |
769 | it has the same sign as the denominator; we'd like to do\r | |
770 | "mod = wx * 0.0", but that may get optimized away */\r | |
771 | mod *= mod; /* hide "mod = +0" from optimizer */\r | |
772 | if (wx < 0.0)\r | |
773 | mod = -mod;\r | |
774 | }\r | |
775 | /* snap quotient to nearest integral value */\r | |
776 | if (div) {\r | |
777 | floordiv = floor(div);\r | |
778 | if (div - floordiv > 0.5)\r | |
779 | floordiv += 1.0;\r | |
780 | }\r | |
781 | else {\r | |
782 | /* div is zero - get the same sign as the true quotient */\r | |
783 | div *= div; /* hide "div = +0" from optimizers */\r | |
784 | floordiv = div * vx / wx; /* zero w/ sign of vx/wx */\r | |
785 | }\r | |
786 | PyFPE_END_PROTECT(floordiv)\r | |
787 | return Py_BuildValue("(dd)", floordiv, mod);\r | |
788 | }\r | |
789 | \r | |
790 | static PyObject *\r | |
791 | float_floor_div(PyObject *v, PyObject *w)\r | |
792 | {\r | |
793 | PyObject *t, *r;\r | |
794 | \r | |
795 | t = float_divmod(v, w);\r | |
796 | if (t == NULL || t == Py_NotImplemented)\r | |
797 | return t;\r | |
798 | assert(PyTuple_CheckExact(t));\r | |
799 | r = PyTuple_GET_ITEM(t, 0);\r | |
800 | Py_INCREF(r);\r | |
801 | Py_DECREF(t);\r | |
802 | return r;\r | |
803 | }\r | |
804 | \r | |
805 | /* determine whether x is an odd integer or not; assumes that\r | |
806 | x is not an infinity or nan. */\r | |
807 | #define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0)\r | |
808 | \r | |
809 | static PyObject *\r | |
810 | float_pow(PyObject *v, PyObject *w, PyObject *z)\r | |
811 | {\r | |
812 | double iv, iw, ix;\r | |
813 | int negate_result = 0;\r | |
814 | \r | |
815 | if ((PyObject *)z != Py_None) {\r | |
816 | PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "\r | |
817 | "allowed unless all arguments are integers");\r | |
818 | return NULL;\r | |
819 | }\r | |
820 | \r | |
821 | CONVERT_TO_DOUBLE(v, iv);\r | |
822 | CONVERT_TO_DOUBLE(w, iw);\r | |
823 | \r | |
824 | /* Sort out special cases here instead of relying on pow() */\r | |
825 | if (iw == 0) { /* v**0 is 1, even 0**0 */\r | |
826 | return PyFloat_FromDouble(1.0);\r | |
827 | }\r | |
828 | if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */\r | |
829 | return PyFloat_FromDouble(iv);\r | |
830 | }\r | |
831 | if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */\r | |
832 | return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);\r | |
833 | }\r | |
834 | if (Py_IS_INFINITY(iw)) {\r | |
835 | /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if\r | |
836 | * abs(v) > 1 (including case where v infinite)\r | |
837 | *\r | |
838 | * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if\r | |
839 | * abs(v) > 1 (including case where v infinite)\r | |
840 | */\r | |
841 | iv = fabs(iv);\r | |
842 | if (iv == 1.0)\r | |
843 | return PyFloat_FromDouble(1.0);\r | |
844 | else if ((iw > 0.0) == (iv > 1.0))\r | |
845 | return PyFloat_FromDouble(fabs(iw)); /* return inf */\r | |
846 | else\r | |
847 | return PyFloat_FromDouble(0.0);\r | |
848 | }\r | |
849 | if (Py_IS_INFINITY(iv)) {\r | |
850 | /* (+-inf)**w is: inf for w positive, 0 for w negative; in\r | |
851 | * both cases, we need to add the appropriate sign if w is\r | |
852 | * an odd integer.\r | |
853 | */\r | |
854 | int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);\r | |
855 | if (iw > 0.0)\r | |
856 | return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));\r | |
857 | else\r | |
858 | return PyFloat_FromDouble(iw_is_odd ?\r | |
859 | copysign(0.0, iv) : 0.0);\r | |
860 | }\r | |
861 | if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero\r | |
862 | (already dealt with above), and an error\r | |
863 | if w is negative. */\r | |
864 | int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);\r | |
865 | if (iw < 0.0) {\r | |
866 | PyErr_SetString(PyExc_ZeroDivisionError,\r | |
867 | "0.0 cannot be raised to a "\r | |
868 | "negative power");\r | |
869 | return NULL;\r | |
870 | }\r | |
871 | /* use correct sign if iw is odd */\r | |
872 | return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);\r | |
873 | }\r | |
874 | \r | |
875 | if (iv < 0.0) {\r | |
876 | /* Whether this is an error is a mess, and bumps into libm\r | |
877 | * bugs so we have to figure it out ourselves.\r | |
878 | */\r | |
879 | if (iw != floor(iw)) {\r | |
880 | PyErr_SetString(PyExc_ValueError, "negative number "\r | |
881 | "cannot be raised to a fractional power");\r | |
882 | return NULL;\r | |
883 | }\r | |
884 | /* iw is an exact integer, albeit perhaps a very large\r | |
885 | * one. Replace iv by its absolute value and remember\r | |
886 | * to negate the pow result if iw is odd.\r | |
887 | */\r | |
888 | iv = -iv;\r | |
889 | negate_result = DOUBLE_IS_ODD_INTEGER(iw);\r | |
890 | }\r | |
891 | \r | |
892 | if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */\r | |
893 | /* (-1) ** large_integer also ends up here. Here's an\r | |
894 | * extract from the comments for the previous\r | |
895 | * implementation explaining why this special case is\r | |
896 | * necessary:\r | |
897 | *\r | |
898 | * -1 raised to an exact integer should never be exceptional.\r | |
899 | * Alas, some libms (chiefly glibc as of early 2003) return\r | |
900 | * NaN and set EDOM on pow(-1, large_int) if the int doesn't\r | |
901 | * happen to be representable in a *C* integer. That's a\r | |
902 | * bug.\r | |
903 | */\r | |
904 | return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);\r | |
905 | }\r | |
906 | \r | |
907 | /* Now iv and iw are finite, iw is nonzero, and iv is\r | |
908 | * positive and not equal to 1.0. We finally allow\r | |
909 | * the platform pow to step in and do the rest.\r | |
910 | */\r | |
911 | errno = 0;\r | |
912 | PyFPE_START_PROTECT("pow", return NULL)\r | |
913 | ix = pow(iv, iw);\r | |
914 | PyFPE_END_PROTECT(ix)\r | |
915 | Py_ADJUST_ERANGE1(ix);\r | |
916 | if (negate_result)\r | |
917 | ix = -ix;\r | |
918 | \r | |
919 | if (errno != 0) {\r | |
920 | /* We don't expect any errno value other than ERANGE, but\r | |
921 | * the range of libm bugs appears unbounded.\r | |
922 | */\r | |
923 | PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :\r | |
924 | PyExc_ValueError);\r | |
925 | return NULL;\r | |
926 | }\r | |
927 | return PyFloat_FromDouble(ix);\r | |
928 | }\r | |
929 | \r | |
930 | #undef DOUBLE_IS_ODD_INTEGER\r | |
931 | \r | |
932 | static PyObject *\r | |
933 | float_neg(PyFloatObject *v)\r | |
934 | {\r | |
935 | return PyFloat_FromDouble(-v->ob_fval);\r | |
936 | }\r | |
937 | \r | |
938 | static PyObject *\r | |
939 | float_abs(PyFloatObject *v)\r | |
940 | {\r | |
941 | return PyFloat_FromDouble(fabs(v->ob_fval));\r | |
942 | }\r | |
943 | \r | |
944 | static int\r | |
945 | float_nonzero(PyFloatObject *v)\r | |
946 | {\r | |
947 | return v->ob_fval != 0.0;\r | |
948 | }\r | |
949 | \r | |
950 | static int\r | |
951 | float_coerce(PyObject **pv, PyObject **pw)\r | |
952 | {\r | |
953 | if (PyInt_Check(*pw)) {\r | |
954 | long x = PyInt_AsLong(*pw);\r | |
955 | *pw = PyFloat_FromDouble((double)x);\r | |
956 | Py_INCREF(*pv);\r | |
957 | return 0;\r | |
958 | }\r | |
959 | else if (PyLong_Check(*pw)) {\r | |
960 | double x = PyLong_AsDouble(*pw);\r | |
961 | if (x == -1.0 && PyErr_Occurred())\r | |
962 | return -1;\r | |
963 | *pw = PyFloat_FromDouble(x);\r | |
964 | Py_INCREF(*pv);\r | |
965 | return 0;\r | |
966 | }\r | |
967 | else if (PyFloat_Check(*pw)) {\r | |
968 | Py_INCREF(*pv);\r | |
969 | Py_INCREF(*pw);\r | |
970 | return 0;\r | |
971 | }\r | |
972 | return 1; /* Can't do it */\r | |
973 | }\r | |
974 | \r | |
975 | static PyObject *\r | |
976 | float_is_integer(PyObject *v)\r | |
977 | {\r | |
978 | double x = PyFloat_AsDouble(v);\r | |
979 | PyObject *o;\r | |
980 | \r | |
981 | if (x == -1.0 && PyErr_Occurred())\r | |
982 | return NULL;\r | |
983 | if (!Py_IS_FINITE(x))\r | |
984 | Py_RETURN_FALSE;\r | |
985 | errno = 0;\r | |
986 | PyFPE_START_PROTECT("is_integer", return NULL)\r | |
987 | o = (floor(x) == x) ? Py_True : Py_False;\r | |
988 | PyFPE_END_PROTECT(x)\r | |
989 | if (errno != 0) {\r | |
990 | PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :\r | |
991 | PyExc_ValueError);\r | |
992 | return NULL;\r | |
993 | }\r | |
994 | Py_INCREF(o);\r | |
995 | return o;\r | |
996 | }\r | |
997 | \r | |
998 | #if 0\r | |
999 | static PyObject *\r | |
1000 | float_is_inf(PyObject *v)\r | |
1001 | {\r | |
1002 | double x = PyFloat_AsDouble(v);\r | |
1003 | if (x == -1.0 && PyErr_Occurred())\r | |
1004 | return NULL;\r | |
1005 | return PyBool_FromLong((long)Py_IS_INFINITY(x));\r | |
1006 | }\r | |
1007 | \r | |
1008 | static PyObject *\r | |
1009 | float_is_nan(PyObject *v)\r | |
1010 | {\r | |
1011 | double x = PyFloat_AsDouble(v);\r | |
1012 | if (x == -1.0 && PyErr_Occurred())\r | |
1013 | return NULL;\r | |
1014 | return PyBool_FromLong((long)Py_IS_NAN(x));\r | |
1015 | }\r | |
1016 | \r | |
1017 | static PyObject *\r | |
1018 | float_is_finite(PyObject *v)\r | |
1019 | {\r | |
1020 | double x = PyFloat_AsDouble(v);\r | |
1021 | if (x == -1.0 && PyErr_Occurred())\r | |
1022 | return NULL;\r | |
1023 | return PyBool_FromLong((long)Py_IS_FINITE(x));\r | |
1024 | }\r | |
1025 | #endif\r | |
1026 | \r | |
1027 | static PyObject *\r | |
1028 | float_trunc(PyObject *v)\r | |
1029 | {\r | |
1030 | double x = PyFloat_AsDouble(v);\r | |
1031 | double wholepart; /* integral portion of x, rounded toward 0 */\r | |
1032 | \r | |
1033 | (void)modf(x, &wholepart);\r | |
1034 | /* Try to get out cheap if this fits in a Python int. The attempt\r | |
1035 | * to cast to long must be protected, as C doesn't define what\r | |
1036 | * happens if the double is too big to fit in a long. Some rare\r | |
1037 | * systems raise an exception then (RISCOS was mentioned as one,\r | |
1038 | * and someone using a non-default option on Sun also bumped into\r | |
1039 | * that). Note that checking for <= LONG_MAX is unsafe: if a long\r | |
1040 | * has more bits of precision than a double, casting LONG_MAX to\r | |
1041 | * double may yield an approximation, and if that's rounded up,\r | |
1042 | * then, e.g., wholepart=LONG_MAX+1 would yield true from the C\r | |
1043 | * expression wholepart<=LONG_MAX, despite that wholepart is\r | |
1044 | * actually greater than LONG_MAX. However, assuming a two's complement\r | |
1045 | * machine with no trap representation, LONG_MIN will be a power of 2 (and\r | |
1046 | * hence exactly representable as a double), and LONG_MAX = -1-LONG_MIN, so\r | |
1047 | * the comparisons with (double)LONG_MIN below should be safe.\r | |
1048 | */\r | |
1049 | if ((double)LONG_MIN <= wholepart && wholepart < -(double)LONG_MIN) {\r | |
1050 | const long aslong = (long)wholepart;\r | |
1051 | return PyInt_FromLong(aslong);\r | |
1052 | }\r | |
1053 | return PyLong_FromDouble(wholepart);\r | |
1054 | }\r | |
1055 | \r | |
1056 | static PyObject *\r | |
1057 | float_long(PyObject *v)\r | |
1058 | {\r | |
1059 | double x = PyFloat_AsDouble(v);\r | |
1060 | return PyLong_FromDouble(x);\r | |
1061 | }\r | |
1062 | \r | |
1063 | /* _Py_double_round: rounds a finite nonzero double to the closest multiple of\r | |
1064 | 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <=\r | |
1065 | ndigits <= 323). Returns a Python float, or sets a Python error and\r | |
1066 | returns NULL on failure (OverflowError and memory errors are possible). */\r | |
1067 | \r | |
1068 | #ifndef PY_NO_SHORT_FLOAT_REPR\r | |
1069 | /* version of _Py_double_round that uses the correctly-rounded string<->double\r | |
1070 | conversions from Python/dtoa.c */\r | |
1071 | \r | |
1072 | /* FIVE_POW_LIMIT is the largest k such that 5**k is exactly representable as\r | |
1073 | a double. Since we're using the code in Python/dtoa.c, it should be safe\r | |
1074 | to assume that C doubles are IEEE 754 binary64 format. To be on the safe\r | |
1075 | side, we check this. */\r | |
1076 | #if DBL_MANT_DIG == 53\r | |
1077 | #define FIVE_POW_LIMIT 22\r | |
1078 | #else\r | |
1079 | #error "C doubles do not appear to be IEEE 754 binary64 format"\r | |
1080 | #endif\r | |
1081 | \r | |
1082 | PyObject *\r | |
1083 | _Py_double_round(double x, int ndigits) {\r | |
1084 | \r | |
1085 | double rounded, m;\r | |
1086 | Py_ssize_t buflen, mybuflen=100;\r | |
1087 | char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;\r | |
1088 | int decpt, sign, val, halfway_case;\r | |
1089 | PyObject *result = NULL;\r | |
1090 | _Py_SET_53BIT_PRECISION_HEADER;\r | |
1091 | \r | |
1092 | /* Easy path for the common case ndigits == 0. */\r | |
1093 | if (ndigits == 0) {\r | |
1094 | rounded = round(x);\r | |
1095 | if (fabs(rounded - x) == 0.5)\r | |
1096 | /* halfway between two integers; use round-away-from-zero */\r | |
1097 | rounded = x + (x > 0.0 ? 0.5 : -0.5);\r | |
1098 | return PyFloat_FromDouble(rounded);\r | |
1099 | }\r | |
1100 | \r | |
1101 | /* The basic idea is very simple: convert and round the double to a\r | |
1102 | decimal string using _Py_dg_dtoa, then convert that decimal string\r | |
1103 | back to a double with _Py_dg_strtod. There's one minor difficulty:\r | |
1104 | Python 2.x expects round to do round-half-away-from-zero, while\r | |
1105 | _Py_dg_dtoa does round-half-to-even. So we need some way to detect\r | |
1106 | and correct the halfway cases.\r | |
1107 | \r | |
1108 | Detection: a halfway value has the form k * 0.5 * 10**-ndigits for\r | |
1109 | some odd integer k. Or in other words, a rational number x is\r | |
1110 | exactly halfway between two multiples of 10**-ndigits if its\r | |
1111 | 2-valuation is exactly -ndigits-1 and its 5-valuation is at least\r | |
1112 | -ndigits. For ndigits >= 0 the latter condition is automatically\r | |
1113 | satisfied for a binary float x, since any such float has\r | |
1114 | nonnegative 5-valuation. For 0 > ndigits >= -22, x needs to be an\r | |
1115 | integral multiple of 5**-ndigits; we can check this using fmod.\r | |
1116 | For -22 > ndigits, there are no halfway cases: 5**23 takes 54 bits\r | |
1117 | to represent exactly, so any odd multiple of 0.5 * 10**n for n >=\r | |
1118 | 23 takes at least 54 bits of precision to represent exactly.\r | |
1119 | \r | |
1120 | Correction: a simple strategy for dealing with halfway cases is to\r | |
1121 | (for the halfway cases only) call _Py_dg_dtoa with an argument of\r | |
1122 | ndigits+1 instead of ndigits (thus doing an exact conversion to\r | |
1123 | decimal), round the resulting string manually, and then convert\r | |
1124 | back using _Py_dg_strtod.\r | |
1125 | */\r | |
1126 | \r | |
1127 | /* nans, infinities and zeros should have already been dealt\r | |
1128 | with by the caller (in this case, builtin_round) */\r | |
1129 | assert(Py_IS_FINITE(x) && x != 0.0);\r | |
1130 | \r | |
1131 | /* find 2-valuation val of x */\r | |
1132 | m = frexp(x, &val);\r | |
1133 | while (m != floor(m)) {\r | |
1134 | m *= 2.0;\r | |
1135 | val--;\r | |
1136 | }\r | |
1137 | \r | |
1138 | /* determine whether this is a halfway case */\r | |
1139 | if (val == -ndigits-1) {\r | |
1140 | if (ndigits >= 0)\r | |
1141 | halfway_case = 1;\r | |
1142 | else if (ndigits >= -FIVE_POW_LIMIT) {\r | |
1143 | double five_pow = 1.0;\r | |
1144 | int i;\r | |
1145 | for (i=0; i < -ndigits; i++)\r | |
1146 | five_pow *= 5.0;\r | |
1147 | halfway_case = fmod(x, five_pow) == 0.0;\r | |
1148 | }\r | |
1149 | else\r | |
1150 | halfway_case = 0;\r | |
1151 | }\r | |
1152 | else\r | |
1153 | halfway_case = 0;\r | |
1154 | \r | |
1155 | /* round to a decimal string; use an extra place for halfway case */\r | |
1156 | _Py_SET_53BIT_PRECISION_START;\r | |
1157 | buf = _Py_dg_dtoa(x, 3, ndigits+halfway_case, &decpt, &sign, &buf_end);\r | |
1158 | _Py_SET_53BIT_PRECISION_END;\r | |
1159 | if (buf == NULL) {\r | |
1160 | PyErr_NoMemory();\r | |
1161 | return NULL;\r | |
1162 | }\r | |
1163 | buflen = buf_end - buf;\r | |
1164 | \r | |
1165 | /* in halfway case, do the round-half-away-from-zero manually */\r | |
1166 | if (halfway_case) {\r | |
1167 | int i, carry;\r | |
1168 | /* sanity check: _Py_dg_dtoa should not have stripped\r | |
1169 | any zeros from the result: there should be exactly\r | |
1170 | ndigits+1 places following the decimal point, and\r | |
1171 | the last digit in the buffer should be a '5'.*/\r | |
1172 | assert(buflen - decpt == ndigits+1);\r | |
1173 | assert(buf[buflen-1] == '5');\r | |
1174 | \r | |
1175 | /* increment and shift right at the same time. */\r | |
1176 | decpt += 1;\r | |
1177 | carry = 1;\r | |
1178 | for (i=buflen-1; i-- > 0;) {\r | |
1179 | carry += buf[i] - '0';\r | |
1180 | buf[i+1] = carry % 10 + '0';\r | |
1181 | carry /= 10;\r | |
1182 | }\r | |
1183 | buf[0] = carry + '0';\r | |
1184 | }\r | |
1185 | \r | |
1186 | /* Get new buffer if shortbuf is too small. Space needed <= buf_end -\r | |
1187 | buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */\r | |
1188 | if (buflen + 8 > mybuflen) {\r | |
1189 | mybuflen = buflen+8;\r | |
1190 | mybuf = (char *)PyMem_Malloc(mybuflen);\r | |
1191 | if (mybuf == NULL) {\r | |
1192 | PyErr_NoMemory();\r | |
1193 | goto exit;\r | |
1194 | }\r | |
1195 | }\r | |
1196 | /* copy buf to mybuf, adding exponent, sign and leading 0 */\r | |
1197 | PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),\r | |
1198 | buf, decpt - (int)buflen);\r | |
1199 | \r | |
1200 | /* and convert the resulting string back to a double */\r | |
1201 | errno = 0;\r | |
1202 | _Py_SET_53BIT_PRECISION_START;\r | |
1203 | rounded = _Py_dg_strtod(mybuf, NULL);\r | |
1204 | _Py_SET_53BIT_PRECISION_END;\r | |
1205 | if (errno == ERANGE && fabs(rounded) >= 1.)\r | |
1206 | PyErr_SetString(PyExc_OverflowError,\r | |
1207 | "rounded value too large to represent");\r | |
1208 | else\r | |
1209 | result = PyFloat_FromDouble(rounded);\r | |
1210 | \r | |
1211 | /* done computing value; now clean up */\r | |
1212 | if (mybuf != shortbuf)\r | |
1213 | PyMem_Free(mybuf);\r | |
1214 | exit:\r | |
1215 | _Py_dg_freedtoa(buf);\r | |
1216 | return result;\r | |
1217 | }\r | |
1218 | \r | |
1219 | #undef FIVE_POW_LIMIT\r | |
1220 | \r | |
1221 | #else /* PY_NO_SHORT_FLOAT_REPR */\r | |
1222 | \r | |
1223 | /* fallback version, to be used when correctly rounded binary<->decimal\r | |
1224 | conversions aren't available */\r | |
1225 | \r | |
1226 | PyObject *\r | |
1227 | _Py_double_round(double x, int ndigits) {\r | |
1228 | double pow1, pow2, y, z;\r | |
1229 | if (ndigits >= 0) {\r | |
1230 | if (ndigits > 22) {\r | |
1231 | /* pow1 and pow2 are each safe from overflow, but\r | |
1232 | pow1*pow2 ~= pow(10.0, ndigits) might overflow */\r | |
1233 | pow1 = pow(10.0, (double)(ndigits-22));\r | |
1234 | pow2 = 1e22;\r | |
1235 | }\r | |
1236 | else {\r | |
1237 | pow1 = pow(10.0, (double)ndigits);\r | |
1238 | pow2 = 1.0;\r | |
1239 | }\r | |
1240 | y = (x*pow1)*pow2;\r | |
1241 | /* if y overflows, then rounded value is exactly x */\r | |
1242 | if (!Py_IS_FINITE(y))\r | |
1243 | return PyFloat_FromDouble(x);\r | |
1244 | }\r | |
1245 | else {\r | |
1246 | pow1 = pow(10.0, (double)-ndigits);\r | |
1247 | pow2 = 1.0; /* unused; silences a gcc compiler warning */\r | |
1248 | y = x / pow1;\r | |
1249 | }\r | |
1250 | \r | |
1251 | z = round(y);\r | |
1252 | if (fabs(y-z) == 0.5)\r | |
1253 | /* halfway between two integers; use round-away-from-zero */\r | |
1254 | z = y + copysign(0.5, y);\r | |
1255 | \r | |
1256 | if (ndigits >= 0)\r | |
1257 | z = (z / pow2) / pow1;\r | |
1258 | else\r | |
1259 | z *= pow1;\r | |
1260 | \r | |
1261 | /* if computation resulted in overflow, raise OverflowError */\r | |
1262 | if (!Py_IS_FINITE(z)) {\r | |
1263 | PyErr_SetString(PyExc_OverflowError,\r | |
1264 | "overflow occurred during round");\r | |
1265 | return NULL;\r | |
1266 | }\r | |
1267 | \r | |
1268 | return PyFloat_FromDouble(z);\r | |
1269 | }\r | |
1270 | \r | |
1271 | #endif /* PY_NO_SHORT_FLOAT_REPR */\r | |
1272 | \r | |
1273 | static PyObject *\r | |
1274 | float_float(PyObject *v)\r | |
1275 | {\r | |
1276 | if (PyFloat_CheckExact(v))\r | |
1277 | Py_INCREF(v);\r | |
1278 | else\r | |
1279 | v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);\r | |
1280 | return v;\r | |
1281 | }\r | |
1282 | \r | |
1283 | /* turn ASCII hex characters into integer values and vice versa */\r | |
1284 | \r | |
1285 | static char\r | |
1286 | char_from_hex(int x)\r | |
1287 | {\r | |
1288 | assert(0 <= x && x < 16);\r | |
1289 | return "0123456789abcdef"[x];\r | |
1290 | }\r | |
1291 | \r | |
1292 | static int\r | |
1293 | hex_from_char(char c) {\r | |
1294 | int x;\r | |
1295 | switch(c) {\r | |
1296 | case '0':\r | |
1297 | x = 0;\r | |
1298 | break;\r | |
1299 | case '1':\r | |
1300 | x = 1;\r | |
1301 | break;\r | |
1302 | case '2':\r | |
1303 | x = 2;\r | |
1304 | break;\r | |
1305 | case '3':\r | |
1306 | x = 3;\r | |
1307 | break;\r | |
1308 | case '4':\r | |
1309 | x = 4;\r | |
1310 | break;\r | |
1311 | case '5':\r | |
1312 | x = 5;\r | |
1313 | break;\r | |
1314 | case '6':\r | |
1315 | x = 6;\r | |
1316 | break;\r | |
1317 | case '7':\r | |
1318 | x = 7;\r | |
1319 | break;\r | |
1320 | case '8':\r | |
1321 | x = 8;\r | |
1322 | break;\r | |
1323 | case '9':\r | |
1324 | x = 9;\r | |
1325 | break;\r | |
1326 | case 'a':\r | |
1327 | case 'A':\r | |
1328 | x = 10;\r | |
1329 | break;\r | |
1330 | case 'b':\r | |
1331 | case 'B':\r | |
1332 | x = 11;\r | |
1333 | break;\r | |
1334 | case 'c':\r | |
1335 | case 'C':\r | |
1336 | x = 12;\r | |
1337 | break;\r | |
1338 | case 'd':\r | |
1339 | case 'D':\r | |
1340 | x = 13;\r | |
1341 | break;\r | |
1342 | case 'e':\r | |
1343 | case 'E':\r | |
1344 | x = 14;\r | |
1345 | break;\r | |
1346 | case 'f':\r | |
1347 | case 'F':\r | |
1348 | x = 15;\r | |
1349 | break;\r | |
1350 | default:\r | |
1351 | x = -1;\r | |
1352 | break;\r | |
1353 | }\r | |
1354 | return x;\r | |
1355 | }\r | |
1356 | \r | |
1357 | /* convert a float to a hexadecimal string */\r | |
1358 | \r | |
1359 | /* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer\r | |
1360 | of the form 4k+1. */\r | |
1361 | #define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4\r | |
1362 | \r | |
1363 | static PyObject *\r | |
1364 | float_hex(PyObject *v)\r | |
1365 | {\r | |
1366 | double x, m;\r | |
1367 | int e, shift, i, si, esign;\r | |
1368 | /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the\r | |
1369 | trailing NUL byte. */\r | |
1370 | char s[(TOHEX_NBITS-1)/4+3];\r | |
1371 | \r | |
1372 | CONVERT_TO_DOUBLE(v, x);\r | |
1373 | \r | |
1374 | if (Py_IS_NAN(x) || Py_IS_INFINITY(x))\r | |
1375 | return float_str((PyFloatObject *)v);\r | |
1376 | \r | |
1377 | if (x == 0.0) {\r | |
1378 | if (copysign(1.0, x) == -1.0)\r | |
1379 | return PyString_FromString("-0x0.0p+0");\r | |
1380 | else\r | |
1381 | return PyString_FromString("0x0.0p+0");\r | |
1382 | }\r | |
1383 | \r | |
1384 | m = frexp(fabs(x), &e);\r | |
1385 | shift = 1 - MAX(DBL_MIN_EXP - e, 0);\r | |
1386 | m = ldexp(m, shift);\r | |
1387 | e -= shift;\r | |
1388 | \r | |
1389 | si = 0;\r | |
1390 | s[si] = char_from_hex((int)m);\r | |
1391 | si++;\r | |
1392 | m -= (int)m;\r | |
1393 | s[si] = '.';\r | |
1394 | si++;\r | |
1395 | for (i=0; i < (TOHEX_NBITS-1)/4; i++) {\r | |
1396 | m *= 16.0;\r | |
1397 | s[si] = char_from_hex((int)m);\r | |
1398 | si++;\r | |
1399 | m -= (int)m;\r | |
1400 | }\r | |
1401 | s[si] = '\0';\r | |
1402 | \r | |
1403 | if (e < 0) {\r | |
1404 | esign = (int)'-';\r | |
1405 | e = -e;\r | |
1406 | }\r | |
1407 | else\r | |
1408 | esign = (int)'+';\r | |
1409 | \r | |
1410 | if (x < 0.0)\r | |
1411 | return PyString_FromFormat("-0x%sp%c%d", s, esign, e);\r | |
1412 | else\r | |
1413 | return PyString_FromFormat("0x%sp%c%d", s, esign, e);\r | |
1414 | }\r | |
1415 | \r | |
1416 | PyDoc_STRVAR(float_hex_doc,\r | |
1417 | "float.hex() -> string\n\\r | |
1418 | \n\\r | |
1419 | Return a hexadecimal representation of a floating-point number.\n\\r | |
1420 | >>> (-0.1).hex()\n\\r | |
1421 | '-0x1.999999999999ap-4'\n\\r | |
1422 | >>> 3.14159.hex()\n\\r | |
1423 | '0x1.921f9f01b866ep+1'");\r | |
1424 | \r | |
1425 | /* Case-insensitive locale-independent string match used for nan and inf\r | |
1426 | detection. t should be lower-case and null-terminated. Return a nonzero\r | |
1427 | result if the first strlen(t) characters of s match t and 0 otherwise. */\r | |
1428 | \r | |
1429 | static int\r | |
1430 | case_insensitive_match(const char *s, const char *t)\r | |
1431 | {\r | |
1432 | while(*t && Py_TOLOWER(*s) == *t) {\r | |
1433 | s++;\r | |
1434 | t++;\r | |
1435 | }\r | |
1436 | return *t ? 0 : 1;\r | |
1437 | }\r | |
1438 | \r | |
1439 | /* Convert a hexadecimal string to a float. */\r | |
1440 | \r | |
1441 | static PyObject *\r | |
1442 | float_fromhex(PyObject *cls, PyObject *arg)\r | |
1443 | {\r | |
1444 | PyObject *result_as_float, *result;\r | |
1445 | double x;\r | |
1446 | long exp, top_exp, lsb, key_digit;\r | |
1447 | char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;\r | |
1448 | int half_eps, digit, round_up, sign=1;\r | |
1449 | Py_ssize_t length, ndigits, fdigits, i;\r | |
1450 | \r | |
1451 | /*\r | |
1452 | * For the sake of simplicity and correctness, we impose an artificial\r | |
1453 | * limit on ndigits, the total number of hex digits in the coefficient\r | |
1454 | * The limit is chosen to ensure that, writing exp for the exponent,\r | |
1455 | *\r | |
1456 | * (1) if exp > LONG_MAX/2 then the value of the hex string is\r | |
1457 | * guaranteed to overflow (provided it's nonzero)\r | |
1458 | *\r | |
1459 | * (2) if exp < LONG_MIN/2 then the value of the hex string is\r | |
1460 | * guaranteed to underflow to 0.\r | |
1461 | *\r | |
1462 | * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of\r | |
1463 | * overflow in the calculation of exp and top_exp below.\r | |
1464 | *\r | |
1465 | * More specifically, ndigits is assumed to satisfy the following\r | |
1466 | * inequalities:\r | |
1467 | *\r | |
1468 | * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2\r | |
1469 | * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP\r | |
1470 | *\r | |
1471 | * If either of these inequalities is not satisfied, a ValueError is\r | |
1472 | * raised. Otherwise, write x for the value of the hex string, and\r | |
1473 | * assume x is nonzero. Then\r | |
1474 | *\r | |
1475 | * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).\r | |
1476 | *\r | |
1477 | * Now if exp > LONG_MAX/2 then:\r | |
1478 | *\r | |
1479 | * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)\r | |
1480 | * = DBL_MAX_EXP\r | |
1481 | *\r | |
1482 | * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C\r | |
1483 | * double, so overflows. If exp < LONG_MIN/2, then\r | |
1484 | *\r | |
1485 | * exp + 4*ndigits <= LONG_MIN/2 - 1 + (\r | |
1486 | * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)\r | |
1487 | * = DBL_MIN_EXP - DBL_MANT_DIG - 1\r | |
1488 | *\r | |
1489 | * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0\r | |
1490 | * when converted to a C double.\r | |
1491 | *\r | |
1492 | * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both\r | |
1493 | * exp+4*ndigits and exp-4*ndigits are within the range of a long.\r | |
1494 | */\r | |
1495 | \r | |
1496 | if (PyString_AsStringAndSize(arg, &s, &length))\r | |
1497 | return NULL;\r | |
1498 | s_end = s + length;\r | |
1499 | \r | |
1500 | /********************\r | |
1501 | * Parse the string *\r | |
1502 | ********************/\r | |
1503 | \r | |
1504 | /* leading whitespace and optional sign */\r | |
1505 | while (Py_ISSPACE(*s))\r | |
1506 | s++;\r | |
1507 | if (*s == '-') {\r | |
1508 | s++;\r | |
1509 | sign = -1;\r | |
1510 | }\r | |
1511 | else if (*s == '+')\r | |
1512 | s++;\r | |
1513 | \r | |
1514 | /* infinities and nans */\r | |
1515 | if (*s == 'i' || *s == 'I') {\r | |
1516 | if (!case_insensitive_match(s+1, "nf"))\r | |
1517 | goto parse_error;\r | |
1518 | s += 3;\r | |
1519 | x = Py_HUGE_VAL;\r | |
1520 | if (case_insensitive_match(s, "inity"))\r | |
1521 | s += 5;\r | |
1522 | goto finished;\r | |
1523 | }\r | |
1524 | if (*s == 'n' || *s == 'N') {\r | |
1525 | if (!case_insensitive_match(s+1, "an"))\r | |
1526 | goto parse_error;\r | |
1527 | s += 3;\r | |
1528 | x = Py_NAN;\r | |
1529 | goto finished;\r | |
1530 | }\r | |
1531 | \r | |
1532 | /* [0x] */\r | |
1533 | s_store = s;\r | |
1534 | if (*s == '0') {\r | |
1535 | s++;\r | |
1536 | if (*s == 'x' || *s == 'X')\r | |
1537 | s++;\r | |
1538 | else\r | |
1539 | s = s_store;\r | |
1540 | }\r | |
1541 | \r | |
1542 | /* coefficient: <integer> [. <fraction>] */\r | |
1543 | coeff_start = s;\r | |
1544 | while (hex_from_char(*s) >= 0)\r | |
1545 | s++;\r | |
1546 | s_store = s;\r | |
1547 | if (*s == '.') {\r | |
1548 | s++;\r | |
1549 | while (hex_from_char(*s) >= 0)\r | |
1550 | s++;\r | |
1551 | coeff_end = s-1;\r | |
1552 | }\r | |
1553 | else\r | |
1554 | coeff_end = s;\r | |
1555 | \r | |
1556 | /* ndigits = total # of hex digits; fdigits = # after point */\r | |
1557 | ndigits = coeff_end - coeff_start;\r | |
1558 | fdigits = coeff_end - s_store;\r | |
1559 | if (ndigits == 0)\r | |
1560 | goto parse_error;\r | |
1561 | if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,\r | |
1562 | LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)\r | |
1563 | goto insane_length_error;\r | |
1564 | \r | |
1565 | /* [p <exponent>] */\r | |
1566 | if (*s == 'p' || *s == 'P') {\r | |
1567 | s++;\r | |
1568 | exp_start = s;\r | |
1569 | if (*s == '-' || *s == '+')\r | |
1570 | s++;\r | |
1571 | if (!('0' <= *s && *s <= '9'))\r | |
1572 | goto parse_error;\r | |
1573 | s++;\r | |
1574 | while ('0' <= *s && *s <= '9')\r | |
1575 | s++;\r | |
1576 | exp = strtol(exp_start, NULL, 10);\r | |
1577 | }\r | |
1578 | else\r | |
1579 | exp = 0;\r | |
1580 | \r | |
1581 | /* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */\r | |
1582 | #define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \\r | |
1583 | coeff_end-(j) : \\r | |
1584 | coeff_end-1-(j)))\r | |
1585 | \r | |
1586 | /*******************************************\r | |
1587 | * Compute rounded value of the hex string *\r | |
1588 | *******************************************/\r | |
1589 | \r | |
1590 | /* Discard leading zeros, and catch extreme overflow and underflow */\r | |
1591 | while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)\r | |
1592 | ndigits--;\r | |
1593 | if (ndigits == 0 || exp < LONG_MIN/2) {\r | |
1594 | x = 0.0;\r | |
1595 | goto finished;\r | |
1596 | }\r | |
1597 | if (exp > LONG_MAX/2)\r | |
1598 | goto overflow_error;\r | |
1599 | \r | |
1600 | /* Adjust exponent for fractional part. */\r | |
1601 | exp = exp - 4*((long)fdigits);\r | |
1602 | \r | |
1603 | /* top_exp = 1 more than exponent of most sig. bit of coefficient */\r | |
1604 | top_exp = exp + 4*((long)ndigits - 1);\r | |
1605 | for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)\r | |
1606 | top_exp++;\r | |
1607 | \r | |
1608 | /* catch almost all nonextreme cases of overflow and underflow here */\r | |
1609 | if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {\r | |
1610 | x = 0.0;\r | |
1611 | goto finished;\r | |
1612 | }\r | |
1613 | if (top_exp > DBL_MAX_EXP)\r | |
1614 | goto overflow_error;\r | |
1615 | \r | |
1616 | /* lsb = exponent of least significant bit of the *rounded* value.\r | |
1617 | This is top_exp - DBL_MANT_DIG unless result is subnormal. */\r | |
1618 | lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;\r | |
1619 | \r | |
1620 | x = 0.0;\r | |
1621 | if (exp >= lsb) {\r | |
1622 | /* no rounding required */\r | |
1623 | for (i = ndigits-1; i >= 0; i--)\r | |
1624 | x = 16.0*x + HEX_DIGIT(i);\r | |
1625 | x = ldexp(x, (int)(exp));\r | |
1626 | goto finished;\r | |
1627 | }\r | |
1628 | /* rounding required. key_digit is the index of the hex digit\r | |
1629 | containing the first bit to be rounded away. */\r | |
1630 | half_eps = 1 << (int)((lsb - exp - 1) % 4);\r | |
1631 | key_digit = (lsb - exp - 1) / 4;\r | |
1632 | for (i = ndigits-1; i > key_digit; i--)\r | |
1633 | x = 16.0*x + HEX_DIGIT(i);\r | |
1634 | digit = HEX_DIGIT(key_digit);\r | |
1635 | x = 16.0*x + (double)(digit & (16-2*half_eps));\r | |
1636 | \r | |
1637 | /* round-half-even: round up if bit lsb-1 is 1 and at least one of\r | |
1638 | bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */\r | |
1639 | if ((digit & half_eps) != 0) {\r | |
1640 | round_up = 0;\r | |
1641 | if ((digit & (3*half_eps-1)) != 0 ||\r | |
1642 | (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))\r | |
1643 | round_up = 1;\r | |
1644 | else\r | |
1645 | for (i = key_digit-1; i >= 0; i--)\r | |
1646 | if (HEX_DIGIT(i) != 0) {\r | |
1647 | round_up = 1;\r | |
1648 | break;\r | |
1649 | }\r | |
1650 | if (round_up == 1) {\r | |
1651 | x += 2*half_eps;\r | |
1652 | if (top_exp == DBL_MAX_EXP &&\r | |
1653 | x == ldexp((double)(2*half_eps), DBL_MANT_DIG))\r | |
1654 | /* overflow corner case: pre-rounded value <\r | |
1655 | 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */\r | |
1656 | goto overflow_error;\r | |
1657 | }\r | |
1658 | }\r | |
1659 | x = ldexp(x, (int)(exp+4*key_digit));\r | |
1660 | \r | |
1661 | finished:\r | |
1662 | /* optional trailing whitespace leading to the end of the string */\r | |
1663 | while (Py_ISSPACE(*s))\r | |
1664 | s++;\r | |
1665 | if (s != s_end)\r | |
1666 | goto parse_error;\r | |
1667 | result_as_float = Py_BuildValue("(d)", sign * x);\r | |
1668 | if (result_as_float == NULL)\r | |
1669 | return NULL;\r | |
1670 | result = PyObject_CallObject(cls, result_as_float);\r | |
1671 | Py_DECREF(result_as_float);\r | |
1672 | return result;\r | |
1673 | \r | |
1674 | overflow_error:\r | |
1675 | PyErr_SetString(PyExc_OverflowError,\r | |
1676 | "hexadecimal value too large to represent as a float");\r | |
1677 | return NULL;\r | |
1678 | \r | |
1679 | parse_error:\r | |
1680 | PyErr_SetString(PyExc_ValueError,\r | |
1681 | "invalid hexadecimal floating-point string");\r | |
1682 | return NULL;\r | |
1683 | \r | |
1684 | insane_length_error:\r | |
1685 | PyErr_SetString(PyExc_ValueError,\r | |
1686 | "hexadecimal string too long to convert");\r | |
1687 | return NULL;\r | |
1688 | }\r | |
1689 | \r | |
1690 | PyDoc_STRVAR(float_fromhex_doc,\r | |
1691 | "float.fromhex(string) -> float\n\\r | |
1692 | \n\\r | |
1693 | Create a floating-point number from a hexadecimal string.\n\\r | |
1694 | >>> float.fromhex('0x1.ffffp10')\n\\r | |
1695 | 2047.984375\n\\r | |
1696 | >>> float.fromhex('-0x1p-1074')\n\\r | |
1697 | -4.9406564584124654e-324");\r | |
1698 | \r | |
1699 | \r | |
1700 | static PyObject *\r | |
1701 | float_as_integer_ratio(PyObject *v, PyObject *unused)\r | |
1702 | {\r | |
1703 | double self;\r | |
1704 | double float_part;\r | |
1705 | int exponent;\r | |
1706 | int i;\r | |
1707 | \r | |
1708 | PyObject *prev;\r | |
1709 | PyObject *py_exponent = NULL;\r | |
1710 | PyObject *numerator = NULL;\r | |
1711 | PyObject *denominator = NULL;\r | |
1712 | PyObject *result_pair = NULL;\r | |
1713 | PyNumberMethods *long_methods = PyLong_Type.tp_as_number;\r | |
1714 | \r | |
1715 | #define INPLACE_UPDATE(obj, call) \\r | |
1716 | prev = obj; \\r | |
1717 | obj = call; \\r | |
1718 | Py_DECREF(prev); \\r | |
1719 | \r | |
1720 | CONVERT_TO_DOUBLE(v, self);\r | |
1721 | \r | |
1722 | if (Py_IS_INFINITY(self)) {\r | |
1723 | PyErr_SetString(PyExc_OverflowError,\r | |
1724 | "Cannot pass infinity to float.as_integer_ratio.");\r | |
1725 | return NULL;\r | |
1726 | }\r | |
1727 | #ifdef Py_NAN\r | |
1728 | if (Py_IS_NAN(self)) {\r | |
1729 | PyErr_SetString(PyExc_ValueError,\r | |
1730 | "Cannot pass NaN to float.as_integer_ratio.");\r | |
1731 | return NULL;\r | |
1732 | }\r | |
1733 | #endif\r | |
1734 | \r | |
1735 | PyFPE_START_PROTECT("as_integer_ratio", goto error);\r | |
1736 | float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */\r | |
1737 | PyFPE_END_PROTECT(float_part);\r | |
1738 | \r | |
1739 | for (i=0; i<300 && float_part != floor(float_part) ; i++) {\r | |
1740 | float_part *= 2.0;\r | |
1741 | exponent--;\r | |
1742 | }\r | |
1743 | /* self == float_part * 2**exponent exactly and float_part is integral.\r | |
1744 | If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part\r | |
1745 | to be truncated by PyLong_FromDouble(). */\r | |
1746 | \r | |
1747 | numerator = PyLong_FromDouble(float_part);\r | |
1748 | if (numerator == NULL) goto error;\r | |
1749 | \r | |
1750 | /* fold in 2**exponent */\r | |
1751 | denominator = PyLong_FromLong(1);\r | |
1752 | py_exponent = PyLong_FromLong(labs((long)exponent));\r | |
1753 | if (py_exponent == NULL) goto error;\r | |
1754 | INPLACE_UPDATE(py_exponent,\r | |
1755 | long_methods->nb_lshift(denominator, py_exponent));\r | |
1756 | if (py_exponent == NULL) goto error;\r | |
1757 | if (exponent > 0) {\r | |
1758 | INPLACE_UPDATE(numerator,\r | |
1759 | long_methods->nb_multiply(numerator, py_exponent));\r | |
1760 | if (numerator == NULL) goto error;\r | |
1761 | }\r | |
1762 | else {\r | |
1763 | Py_DECREF(denominator);\r | |
1764 | denominator = py_exponent;\r | |
1765 | py_exponent = NULL;\r | |
1766 | }\r | |
1767 | \r | |
1768 | /* Returns ints instead of longs where possible */\r | |
1769 | INPLACE_UPDATE(numerator, PyNumber_Int(numerator));\r | |
1770 | if (numerator == NULL) goto error;\r | |
1771 | INPLACE_UPDATE(denominator, PyNumber_Int(denominator));\r | |
1772 | if (denominator == NULL) goto error;\r | |
1773 | \r | |
1774 | result_pair = PyTuple_Pack(2, numerator, denominator);\r | |
1775 | \r | |
1776 | #undef INPLACE_UPDATE\r | |
1777 | error:\r | |
1778 | Py_XDECREF(py_exponent);\r | |
1779 | Py_XDECREF(denominator);\r | |
1780 | Py_XDECREF(numerator);\r | |
1781 | return result_pair;\r | |
1782 | }\r | |
1783 | \r | |
1784 | PyDoc_STRVAR(float_as_integer_ratio_doc,\r | |
1785 | "float.as_integer_ratio() -> (int, int)\n"\r | |
1786 | "\n"\r | |
1787 | "Return a pair of integers, whose ratio is exactly equal to the original\n"\r | |
1788 | "float and with a positive denominator.\n"\r | |
1789 | "Raise OverflowError on infinities and a ValueError on NaNs.\n"\r | |
1790 | "\n"\r | |
1791 | ">>> (10.0).as_integer_ratio()\n"\r | |
1792 | "(10, 1)\n"\r | |
1793 | ">>> (0.0).as_integer_ratio()\n"\r | |
1794 | "(0, 1)\n"\r | |
1795 | ">>> (-.25).as_integer_ratio()\n"\r | |
1796 | "(-1, 4)");\r | |
1797 | \r | |
1798 | \r | |
1799 | static PyObject *\r | |
1800 | float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);\r | |
1801 | \r | |
1802 | static PyObject *\r | |
1803 | float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\r | |
1804 | {\r | |
1805 | PyObject *x = Py_False; /* Integer zero */\r | |
1806 | static char *kwlist[] = {"x", 0};\r | |
1807 | \r | |
1808 | if (type != &PyFloat_Type)\r | |
1809 | return float_subtype_new(type, args, kwds); /* Wimp out */\r | |
1810 | if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))\r | |
1811 | return NULL;\r | |
1812 | /* If it's a string, but not a string subclass, use\r | |
1813 | PyFloat_FromString. */\r | |
1814 | if (PyString_CheckExact(x))\r | |
1815 | return PyFloat_FromString(x, NULL);\r | |
1816 | return PyNumber_Float(x);\r | |
1817 | }\r | |
1818 | \r | |
1819 | /* Wimpy, slow approach to tp_new calls for subtypes of float:\r | |
1820 | first create a regular float from whatever arguments we got,\r | |
1821 | then allocate a subtype instance and initialize its ob_fval\r | |
1822 | from the regular float. The regular float is then thrown away.\r | |
1823 | */\r | |
1824 | static PyObject *\r | |
1825 | float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\r | |
1826 | {\r | |
1827 | PyObject *tmp, *newobj;\r | |
1828 | \r | |
1829 | assert(PyType_IsSubtype(type, &PyFloat_Type));\r | |
1830 | tmp = float_new(&PyFloat_Type, args, kwds);\r | |
1831 | if (tmp == NULL)\r | |
1832 | return NULL;\r | |
1833 | assert(PyFloat_CheckExact(tmp));\r | |
1834 | newobj = type->tp_alloc(type, 0);\r | |
1835 | if (newobj == NULL) {\r | |
1836 | Py_DECREF(tmp);\r | |
1837 | return NULL;\r | |
1838 | }\r | |
1839 | ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;\r | |
1840 | Py_DECREF(tmp);\r | |
1841 | return newobj;\r | |
1842 | }\r | |
1843 | \r | |
1844 | static PyObject *\r | |
1845 | float_getnewargs(PyFloatObject *v)\r | |
1846 | {\r | |
1847 | return Py_BuildValue("(d)", v->ob_fval);\r | |
1848 | }\r | |
1849 | \r | |
1850 | /* this is for the benefit of the pack/unpack routines below */\r | |
1851 | \r | |
1852 | typedef enum {\r | |
1853 | unknown_format, ieee_big_endian_format, ieee_little_endian_format\r | |
1854 | } float_format_type;\r | |
1855 | \r | |
1856 | static float_format_type double_format, float_format;\r | |
1857 | static float_format_type detected_double_format, detected_float_format;\r | |
1858 | \r | |
1859 | static PyObject *\r | |
1860 | float_getformat(PyTypeObject *v, PyObject* arg)\r | |
1861 | {\r | |
1862 | char* s;\r | |
1863 | float_format_type r;\r | |
1864 | \r | |
1865 | if (!PyString_Check(arg)) {\r | |
1866 | PyErr_Format(PyExc_TypeError,\r | |
1867 | "__getformat__() argument must be string, not %.500s",\r | |
1868 | Py_TYPE(arg)->tp_name);\r | |
1869 | return NULL;\r | |
1870 | }\r | |
1871 | s = PyString_AS_STRING(arg);\r | |
1872 | if (strcmp(s, "double") == 0) {\r | |
1873 | r = double_format;\r | |
1874 | }\r | |
1875 | else if (strcmp(s, "float") == 0) {\r | |
1876 | r = float_format;\r | |
1877 | }\r | |
1878 | else {\r | |
1879 | PyErr_SetString(PyExc_ValueError,\r | |
1880 | "__getformat__() argument 1 must be "\r | |
1881 | "'double' or 'float'");\r | |
1882 | return NULL;\r | |
1883 | }\r | |
1884 | \r | |
1885 | switch (r) {\r | |
1886 | case unknown_format:\r | |
1887 | return PyString_FromString("unknown");\r | |
1888 | case ieee_little_endian_format:\r | |
1889 | return PyString_FromString("IEEE, little-endian");\r | |
1890 | case ieee_big_endian_format:\r | |
1891 | return PyString_FromString("IEEE, big-endian");\r | |
1892 | default:\r | |
1893 | Py_FatalError("insane float_format or double_format");\r | |
1894 | return NULL;\r | |
1895 | }\r | |
1896 | }\r | |
1897 | \r | |
1898 | PyDoc_STRVAR(float_getformat_doc,\r | |
1899 | "float.__getformat__(typestr) -> string\n"\r | |
1900 | "\n"\r | |
1901 | "You probably don't want to use this function. It exists mainly to be\n"\r | |
1902 | "used in Python's test suite.\n"\r | |
1903 | "\n"\r | |
1904 | "typestr must be 'double' or 'float'. This function returns whichever of\n"\r | |
1905 | "'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n"\r | |
1906 | "format of floating point numbers used by the C type named by typestr.");\r | |
1907 | \r | |
1908 | static PyObject *\r | |
1909 | float_setformat(PyTypeObject *v, PyObject* args)\r | |
1910 | {\r | |
1911 | char* typestr;\r | |
1912 | char* format;\r | |
1913 | float_format_type f;\r | |
1914 | float_format_type detected;\r | |
1915 | float_format_type *p;\r | |
1916 | \r | |
1917 | if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))\r | |
1918 | return NULL;\r | |
1919 | \r | |
1920 | if (strcmp(typestr, "double") == 0) {\r | |
1921 | p = &double_format;\r | |
1922 | detected = detected_double_format;\r | |
1923 | }\r | |
1924 | else if (strcmp(typestr, "float") == 0) {\r | |
1925 | p = &float_format;\r | |
1926 | detected = detected_float_format;\r | |
1927 | }\r | |
1928 | else {\r | |
1929 | PyErr_SetString(PyExc_ValueError,\r | |
1930 | "__setformat__() argument 1 must "\r | |
1931 | "be 'double' or 'float'");\r | |
1932 | return NULL;\r | |
1933 | }\r | |
1934 | \r | |
1935 | if (strcmp(format, "unknown") == 0) {\r | |
1936 | f = unknown_format;\r | |
1937 | }\r | |
1938 | else if (strcmp(format, "IEEE, little-endian") == 0) {\r | |
1939 | f = ieee_little_endian_format;\r | |
1940 | }\r | |
1941 | else if (strcmp(format, "IEEE, big-endian") == 0) {\r | |
1942 | f = ieee_big_endian_format;\r | |
1943 | }\r | |
1944 | else {\r | |
1945 | PyErr_SetString(PyExc_ValueError,\r | |
1946 | "__setformat__() argument 2 must be "\r | |
1947 | "'unknown', 'IEEE, little-endian' or "\r | |
1948 | "'IEEE, big-endian'");\r | |
1949 | return NULL;\r | |
1950 | \r | |
1951 | }\r | |
1952 | \r | |
1953 | if (f != unknown_format && f != detected) {\r | |
1954 | PyErr_Format(PyExc_ValueError,\r | |
1955 | "can only set %s format to 'unknown' or the "\r | |
1956 | "detected platform value", typestr);\r | |
1957 | return NULL;\r | |
1958 | }\r | |
1959 | \r | |
1960 | *p = f;\r | |
1961 | Py_RETURN_NONE;\r | |
1962 | }\r | |
1963 | \r | |
1964 | PyDoc_STRVAR(float_setformat_doc,\r | |
1965 | "float.__setformat__(typestr, fmt) -> None\n"\r | |
1966 | "\n"\r | |
1967 | "You probably don't want to use this function. It exists mainly to be\n"\r | |
1968 | "used in Python's test suite.\n"\r | |
1969 | "\n"\r | |
1970 | "typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n"\r | |
1971 | "'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n"\r | |
1972 | "one of the latter two if it appears to match the underlying C reality.\n"\r | |
1973 | "\n"\r | |
1974 | "Override the automatic determination of C-level floating point type.\n"\r | |
1975 | "This affects how floats are converted to and from binary strings.");\r | |
1976 | \r | |
1977 | static PyObject *\r | |
1978 | float_getzero(PyObject *v, void *closure)\r | |
1979 | {\r | |
1980 | return PyFloat_FromDouble(0.0);\r | |
1981 | }\r | |
1982 | \r | |
1983 | static PyObject *\r | |
1984 | float__format__(PyObject *self, PyObject *args)\r | |
1985 | {\r | |
1986 | PyObject *format_spec;\r | |
1987 | \r | |
1988 | if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))\r | |
1989 | return NULL;\r | |
1990 | if (PyBytes_Check(format_spec))\r | |
1991 | return _PyFloat_FormatAdvanced(self,\r | |
1992 | PyBytes_AS_STRING(format_spec),\r | |
1993 | PyBytes_GET_SIZE(format_spec));\r | |
1994 | if (PyUnicode_Check(format_spec)) {\r | |
1995 | /* Convert format_spec to a str */\r | |
1996 | PyObject *result;\r | |
1997 | PyObject *str_spec = PyObject_Str(format_spec);\r | |
1998 | \r | |
1999 | if (str_spec == NULL)\r | |
2000 | return NULL;\r | |
2001 | \r | |
2002 | result = _PyFloat_FormatAdvanced(self,\r | |
2003 | PyBytes_AS_STRING(str_spec),\r | |
2004 | PyBytes_GET_SIZE(str_spec));\r | |
2005 | \r | |
2006 | Py_DECREF(str_spec);\r | |
2007 | return result;\r | |
2008 | }\r | |
2009 | PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");\r | |
2010 | return NULL;\r | |
2011 | }\r | |
2012 | \r | |
2013 | PyDoc_STRVAR(float__format__doc,\r | |
2014 | "float.__format__(format_spec) -> string\n"\r | |
2015 | "\n"\r | |
2016 | "Formats the float according to format_spec.");\r | |
2017 | \r | |
2018 | \r | |
2019 | static PyMethodDef float_methods[] = {\r | |
2020 | {"conjugate", (PyCFunction)float_float, METH_NOARGS,\r | |
2021 | "Return self, the complex conjugate of any float."},\r | |
2022 | {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,\r | |
2023 | "Return the Integral closest to x between 0 and x."},\r | |
2024 | {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,\r | |
2025 | float_as_integer_ratio_doc},\r | |
2026 | {"fromhex", (PyCFunction)float_fromhex,\r | |
2027 | METH_O|METH_CLASS, float_fromhex_doc},\r | |
2028 | {"hex", (PyCFunction)float_hex,\r | |
2029 | METH_NOARGS, float_hex_doc},\r | |
2030 | {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,\r | |
2031 | "Return True if the float is an integer."},\r | |
2032 | #if 0\r | |
2033 | {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,\r | |
2034 | "Return True if the float is positive or negative infinite."},\r | |
2035 | {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,\r | |
2036 | "Return True if the float is finite, neither infinite nor NaN."},\r | |
2037 | {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,\r | |
2038 | "Return True if the float is not a number (NaN)."},\r | |
2039 | #endif\r | |
2040 | {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},\r | |
2041 | {"__getformat__", (PyCFunction)float_getformat,\r | |
2042 | METH_O|METH_CLASS, float_getformat_doc},\r | |
2043 | {"__setformat__", (PyCFunction)float_setformat,\r | |
2044 | METH_VARARGS|METH_CLASS, float_setformat_doc},\r | |
2045 | {"__format__", (PyCFunction)float__format__,\r | |
2046 | METH_VARARGS, float__format__doc},\r | |
2047 | {NULL, NULL} /* sentinel */\r | |
2048 | };\r | |
2049 | \r | |
2050 | static PyGetSetDef float_getset[] = {\r | |
2051 | {"real",\r | |
2052 | (getter)float_float, (setter)NULL,\r | |
2053 | "the real part of a complex number",\r | |
2054 | NULL},\r | |
2055 | {"imag",\r | |
2056 | (getter)float_getzero, (setter)NULL,\r | |
2057 | "the imaginary part of a complex number",\r | |
2058 | NULL},\r | |
2059 | {NULL} /* Sentinel */\r | |
2060 | };\r | |
2061 | \r | |
2062 | PyDoc_STRVAR(float_doc,\r | |
2063 | "float(x) -> floating point number\n\\r | |
2064 | \n\\r | |
2065 | Convert a string or number to a floating point number, if possible.");\r | |
2066 | \r | |
2067 | \r | |
2068 | static PyNumberMethods float_as_number = {\r | |
2069 | float_add, /*nb_add*/\r | |
2070 | float_sub, /*nb_subtract*/\r | |
2071 | float_mul, /*nb_multiply*/\r | |
2072 | float_classic_div, /*nb_divide*/\r | |
2073 | float_rem, /*nb_remainder*/\r | |
2074 | float_divmod, /*nb_divmod*/\r | |
2075 | float_pow, /*nb_power*/\r | |
2076 | (unaryfunc)float_neg, /*nb_negative*/\r | |
2077 | (unaryfunc)float_float, /*nb_positive*/\r | |
2078 | (unaryfunc)float_abs, /*nb_absolute*/\r | |
2079 | (inquiry)float_nonzero, /*nb_nonzero*/\r | |
2080 | 0, /*nb_invert*/\r | |
2081 | 0, /*nb_lshift*/\r | |
2082 | 0, /*nb_rshift*/\r | |
2083 | 0, /*nb_and*/\r | |
2084 | 0, /*nb_xor*/\r | |
2085 | 0, /*nb_or*/\r | |
2086 | float_coerce, /*nb_coerce*/\r | |
2087 | float_trunc, /*nb_int*/\r | |
2088 | float_long, /*nb_long*/\r | |
2089 | float_float, /*nb_float*/\r | |
2090 | 0, /* nb_oct */\r | |
2091 | 0, /* nb_hex */\r | |
2092 | 0, /* nb_inplace_add */\r | |
2093 | 0, /* nb_inplace_subtract */\r | |
2094 | 0, /* nb_inplace_multiply */\r | |
2095 | 0, /* nb_inplace_divide */\r | |
2096 | 0, /* nb_inplace_remainder */\r | |
2097 | 0, /* nb_inplace_power */\r | |
2098 | 0, /* nb_inplace_lshift */\r | |
2099 | 0, /* nb_inplace_rshift */\r | |
2100 | 0, /* nb_inplace_and */\r | |
2101 | 0, /* nb_inplace_xor */\r | |
2102 | 0, /* nb_inplace_or */\r | |
2103 | float_floor_div, /* nb_floor_divide */\r | |
2104 | float_div, /* nb_true_divide */\r | |
2105 | 0, /* nb_inplace_floor_divide */\r | |
2106 | 0, /* nb_inplace_true_divide */\r | |
2107 | };\r | |
2108 | \r | |
2109 | PyTypeObject PyFloat_Type = {\r | |
2110 | PyVarObject_HEAD_INIT(&PyType_Type, 0)\r | |
2111 | "float",\r | |
2112 | sizeof(PyFloatObject),\r | |
2113 | 0,\r | |
2114 | (destructor)float_dealloc, /* tp_dealloc */\r | |
2115 | (printfunc)float_print, /* tp_print */\r | |
2116 | 0, /* tp_getattr */\r | |
2117 | 0, /* tp_setattr */\r | |
2118 | 0, /* tp_compare */\r | |
2119 | (reprfunc)float_repr, /* tp_repr */\r | |
2120 | &float_as_number, /* tp_as_number */\r | |
2121 | 0, /* tp_as_sequence */\r | |
2122 | 0, /* tp_as_mapping */\r | |
2123 | (hashfunc)float_hash, /* tp_hash */\r | |
2124 | 0, /* tp_call */\r | |
2125 | (reprfunc)float_str, /* tp_str */\r | |
2126 | PyObject_GenericGetAttr, /* tp_getattro */\r | |
2127 | 0, /* tp_setattro */\r | |
2128 | 0, /* tp_as_buffer */\r | |
2129 | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |\r | |
2130 | Py_TPFLAGS_BASETYPE, /* tp_flags */\r | |
2131 | float_doc, /* tp_doc */\r | |
2132 | 0, /* tp_traverse */\r | |
2133 | 0, /* tp_clear */\r | |
2134 | float_richcompare, /* tp_richcompare */\r | |
2135 | 0, /* tp_weaklistoffset */\r | |
2136 | 0, /* tp_iter */\r | |
2137 | 0, /* tp_iternext */\r | |
2138 | float_methods, /* tp_methods */\r | |
2139 | 0, /* tp_members */\r | |
2140 | float_getset, /* tp_getset */\r | |
2141 | 0, /* tp_base */\r | |
2142 | 0, /* tp_dict */\r | |
2143 | 0, /* tp_descr_get */\r | |
2144 | 0, /* tp_descr_set */\r | |
2145 | 0, /* tp_dictoffset */\r | |
2146 | 0, /* tp_init */\r | |
2147 | 0, /* tp_alloc */\r | |
2148 | float_new, /* tp_new */\r | |
2149 | };\r | |
2150 | \r | |
2151 | void\r | |
2152 | _PyFloat_Init(void)\r | |
2153 | {\r | |
2154 | /* We attempt to determine if this machine is using IEEE\r | |
2155 | floating point formats by peering at the bits of some\r | |
2156 | carefully chosen values. If it looks like we are on an\r | |
2157 | IEEE platform, the float packing/unpacking routines can\r | |
2158 | just copy bits, if not they resort to arithmetic & shifts\r | |
2159 | and masks. The shifts & masks approach works on all finite\r | |
2160 | values, but what happens to infinities, NaNs and signed\r | |
2161 | zeroes on packing is an accident, and attempting to unpack\r | |
2162 | a NaN or an infinity will raise an exception.\r | |
2163 | \r | |
2164 | Note that if we're on some whacked-out platform which uses\r | |
2165 | IEEE formats but isn't strictly little-endian or big-\r | |
2166 | endian, we will fall back to the portable shifts & masks\r | |
2167 | method. */\r | |
2168 | \r | |
2169 | #if SIZEOF_DOUBLE == 8\r | |
2170 | {\r | |
2171 | double x = 9006104071832581.0;\r | |
2172 | if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)\r | |
2173 | detected_double_format = ieee_big_endian_format;\r | |
2174 | else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)\r | |
2175 | detected_double_format = ieee_little_endian_format;\r | |
2176 | else\r | |
2177 | detected_double_format = unknown_format;\r | |
2178 | }\r | |
2179 | #else\r | |
2180 | detected_double_format = unknown_format;\r | |
2181 | #endif\r | |
2182 | \r | |
2183 | #if SIZEOF_FLOAT == 4\r | |
2184 | {\r | |
2185 | float y = 16711938.0;\r | |
2186 | if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)\r | |
2187 | detected_float_format = ieee_big_endian_format;\r | |
2188 | else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)\r | |
2189 | detected_float_format = ieee_little_endian_format;\r | |
2190 | else\r | |
2191 | detected_float_format = unknown_format;\r | |
2192 | }\r | |
2193 | #else\r | |
2194 | detected_float_format = unknown_format;\r | |
2195 | #endif\r | |
2196 | \r | |
2197 | double_format = detected_double_format;\r | |
2198 | float_format = detected_float_format;\r | |
2199 | \r | |
2200 | /* Init float info */\r | |
2201 | if (FloatInfoType.tp_name == 0)\r | |
2202 | PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);\r | |
2203 | }\r | |
2204 | \r | |
2205 | int\r | |
2206 | PyFloat_ClearFreeList(void)\r | |
2207 | {\r | |
2208 | PyFloatObject *p;\r | |
2209 | PyFloatBlock *list, *next;\r | |
2210 | int i;\r | |
2211 | int u; /* remaining unfreed ints per block */\r | |
2212 | int freelist_size = 0;\r | |
2213 | \r | |
2214 | list = block_list;\r | |
2215 | block_list = NULL;\r | |
2216 | free_list = NULL;\r | |
2217 | while (list != NULL) {\r | |
2218 | u = 0;\r | |
2219 | for (i = 0, p = &list->objects[0];\r | |
2220 | i < N_FLOATOBJECTS;\r | |
2221 | i++, p++) {\r | |
2222 | if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)\r | |
2223 | u++;\r | |
2224 | }\r | |
2225 | next = list->next;\r | |
2226 | if (u) {\r | |
2227 | list->next = block_list;\r | |
2228 | block_list = list;\r | |
2229 | for (i = 0, p = &list->objects[0];\r | |
2230 | i < N_FLOATOBJECTS;\r | |
2231 | i++, p++) {\r | |
2232 | if (!PyFloat_CheckExact(p) ||\r | |
2233 | Py_REFCNT(p) == 0) {\r | |
2234 | Py_TYPE(p) = (struct _typeobject *)\r | |
2235 | free_list;\r | |
2236 | free_list = p;\r | |
2237 | }\r | |
2238 | }\r | |
2239 | }\r | |
2240 | else {\r | |
2241 | PyMem_FREE(list);\r | |
2242 | }\r | |
2243 | freelist_size += u;\r | |
2244 | list = next;\r | |
2245 | }\r | |
2246 | return freelist_size;\r | |
2247 | }\r | |
2248 | \r | |
2249 | void\r | |
2250 | PyFloat_Fini(void)\r | |
2251 | {\r | |
2252 | PyFloatObject *p;\r | |
2253 | PyFloatBlock *list;\r | |
2254 | int i;\r | |
2255 | int u; /* total unfreed floats per block */\r | |
2256 | \r | |
2257 | u = PyFloat_ClearFreeList();\r | |
2258 | \r | |
2259 | if (!Py_VerboseFlag)\r | |
2260 | return;\r | |
2261 | fprintf(stderr, "# cleanup floats");\r | |
2262 | if (!u) {\r | |
2263 | fprintf(stderr, "\n");\r | |
2264 | }\r | |
2265 | else {\r | |
2266 | fprintf(stderr,\r | |
2267 | ": %d unfreed float%s\n",\r | |
2268 | u, u == 1 ? "" : "s");\r | |
2269 | }\r | |
2270 | if (Py_VerboseFlag > 1) {\r | |
2271 | list = block_list;\r | |
2272 | while (list != NULL) {\r | |
2273 | for (i = 0, p = &list->objects[0];\r | |
2274 | i < N_FLOATOBJECTS;\r | |
2275 | i++, p++) {\r | |
2276 | if (PyFloat_CheckExact(p) &&\r | |
2277 | Py_REFCNT(p) != 0) {\r | |
2278 | char *buf = PyOS_double_to_string(\r | |
2279 | PyFloat_AS_DOUBLE(p), 'r',\r | |
2280 | 0, 0, NULL);\r | |
2281 | if (buf) {\r | |
2282 | /* XXX(twouters) cast\r | |
2283 | refcount to long\r | |
2284 | until %zd is\r | |
2285 | universally\r | |
2286 | available\r | |
2287 | */\r | |
2288 | fprintf(stderr,\r | |
2289 | "# <float at %p, refcnt=%ld, val=%s>\n",\r | |
2290 | p, (long)Py_REFCNT(p), buf);\r | |
2291 | PyMem_Free(buf);\r | |
2292 | }\r | |
2293 | }\r | |
2294 | }\r | |
2295 | list = list->next;\r | |
2296 | }\r | |
2297 | }\r | |
2298 | }\r | |
2299 | \r | |
2300 | /*----------------------------------------------------------------------------\r | |
2301 | * _PyFloat_{Pack,Unpack}{4,8}. See floatobject.h.\r | |
2302 | */\r | |
2303 | int\r | |
2304 | _PyFloat_Pack4(double x, unsigned char *p, int le)\r | |
2305 | {\r | |
2306 | if (float_format == unknown_format) {\r | |
2307 | unsigned char sign;\r | |
2308 | int e;\r | |
2309 | double f;\r | |
2310 | unsigned int fbits;\r | |
2311 | int incr = 1;\r | |
2312 | \r | |
2313 | if (le) {\r | |
2314 | p += 3;\r | |
2315 | incr = -1;\r | |
2316 | }\r | |
2317 | \r | |
2318 | if (x < 0) {\r | |
2319 | sign = 1;\r | |
2320 | x = -x;\r | |
2321 | }\r | |
2322 | else\r | |
2323 | sign = 0;\r | |
2324 | \r | |
2325 | f = frexp(x, &e);\r | |
2326 | \r | |
2327 | /* Normalize f to be in the range [1.0, 2.0) */\r | |
2328 | if (0.5 <= f && f < 1.0) {\r | |
2329 | f *= 2.0;\r | |
2330 | e--;\r | |
2331 | }\r | |
2332 | else if (f == 0.0)\r | |
2333 | e = 0;\r | |
2334 | else {\r | |
2335 | PyErr_SetString(PyExc_SystemError,\r | |
2336 | "frexp() result out of range");\r | |
2337 | return -1;\r | |
2338 | }\r | |
2339 | \r | |
2340 | if (e >= 128)\r | |
2341 | goto Overflow;\r | |
2342 | else if (e < -126) {\r | |
2343 | /* Gradual underflow */\r | |
2344 | f = ldexp(f, 126 + e);\r | |
2345 | e = 0;\r | |
2346 | }\r | |
2347 | else if (!(e == 0 && f == 0.0)) {\r | |
2348 | e += 127;\r | |
2349 | f -= 1.0; /* Get rid of leading 1 */\r | |
2350 | }\r | |
2351 | \r | |
2352 | f *= 8388608.0; /* 2**23 */\r | |
2353 | fbits = (unsigned int)(f + 0.5); /* Round */\r | |
2354 | assert(fbits <= 8388608);\r | |
2355 | if (fbits >> 23) {\r | |
2356 | /* The carry propagated out of a string of 23 1 bits. */\r | |
2357 | fbits = 0;\r | |
2358 | ++e;\r | |
2359 | if (e >= 255)\r | |
2360 | goto Overflow;\r | |
2361 | }\r | |
2362 | \r | |
2363 | /* First byte */\r | |
2364 | *p = (sign << 7) | (e >> 1);\r | |
2365 | p += incr;\r | |
2366 | \r | |
2367 | /* Second byte */\r | |
2368 | *p = (char) (((e & 1) << 7) | (fbits >> 16));\r | |
2369 | p += incr;\r | |
2370 | \r | |
2371 | /* Third byte */\r | |
2372 | *p = (fbits >> 8) & 0xFF;\r | |
2373 | p += incr;\r | |
2374 | \r | |
2375 | /* Fourth byte */\r | |
2376 | *p = fbits & 0xFF;\r | |
2377 | \r | |
2378 | /* Done */\r | |
2379 | return 0;\r | |
2380 | \r | |
2381 | }\r | |
2382 | else {\r | |
2383 | float y = (float)x;\r | |
2384 | const char *s = (char*)&y;\r | |
2385 | int i, incr = 1;\r | |
2386 | \r | |
2387 | if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))\r | |
2388 | goto Overflow;\r | |
2389 | \r | |
2390 | if ((float_format == ieee_little_endian_format && !le)\r | |
2391 | || (float_format == ieee_big_endian_format && le)) {\r | |
2392 | p += 3;\r | |
2393 | incr = -1;\r | |
2394 | }\r | |
2395 | \r | |
2396 | for (i = 0; i < 4; i++) {\r | |
2397 | *p = *s++;\r | |
2398 | p += incr;\r | |
2399 | }\r | |
2400 | return 0;\r | |
2401 | }\r | |
2402 | Overflow:\r | |
2403 | PyErr_SetString(PyExc_OverflowError,\r | |
2404 | "float too large to pack with f format");\r | |
2405 | return -1;\r | |
2406 | }\r | |
2407 | \r | |
2408 | int\r | |
2409 | _PyFloat_Pack8(double x, unsigned char *p, int le)\r | |
2410 | {\r | |
2411 | if (double_format == unknown_format) {\r | |
2412 | unsigned char sign;\r | |
2413 | int e;\r | |
2414 | double f;\r | |
2415 | unsigned int fhi, flo;\r | |
2416 | int incr = 1;\r | |
2417 | \r | |
2418 | if (le) {\r | |
2419 | p += 7;\r | |
2420 | incr = -1;\r | |
2421 | }\r | |
2422 | \r | |
2423 | if (x < 0) {\r | |
2424 | sign = 1;\r | |
2425 | x = -x;\r | |
2426 | }\r | |
2427 | else\r | |
2428 | sign = 0;\r | |
2429 | \r | |
2430 | f = frexp(x, &e);\r | |
2431 | \r | |
2432 | /* Normalize f to be in the range [1.0, 2.0) */\r | |
2433 | if (0.5 <= f && f < 1.0) {\r | |
2434 | f *= 2.0;\r | |
2435 | e--;\r | |
2436 | }\r | |
2437 | else if (f == 0.0)\r | |
2438 | e = 0;\r | |
2439 | else {\r | |
2440 | PyErr_SetString(PyExc_SystemError,\r | |
2441 | "frexp() result out of range");\r | |
2442 | return -1;\r | |
2443 | }\r | |
2444 | \r | |
2445 | if (e >= 1024)\r | |
2446 | goto Overflow;\r | |
2447 | else if (e < -1022) {\r | |
2448 | /* Gradual underflow */\r | |
2449 | f = ldexp(f, 1022 + e);\r | |
2450 | e = 0;\r | |
2451 | }\r | |
2452 | else if (!(e == 0 && f == 0.0)) {\r | |
2453 | e += 1023;\r | |
2454 | f -= 1.0; /* Get rid of leading 1 */\r | |
2455 | }\r | |
2456 | \r | |
2457 | /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */\r | |
2458 | f *= 268435456.0; /* 2**28 */\r | |
2459 | fhi = (unsigned int)f; /* Truncate */\r | |
2460 | assert(fhi < 268435456);\r | |
2461 | \r | |
2462 | f -= (double)fhi;\r | |
2463 | f *= 16777216.0; /* 2**24 */\r | |
2464 | flo = (unsigned int)(f + 0.5); /* Round */\r | |
2465 | assert(flo <= 16777216);\r | |
2466 | if (flo >> 24) {\r | |
2467 | /* The carry propagated out of a string of 24 1 bits. */\r | |
2468 | flo = 0;\r | |
2469 | ++fhi;\r | |
2470 | if (fhi >> 28) {\r | |
2471 | /* And it also progagated out of the next 28 bits. */\r | |
2472 | fhi = 0;\r | |
2473 | ++e;\r | |
2474 | if (e >= 2047)\r | |
2475 | goto Overflow;\r | |
2476 | }\r | |
2477 | }\r | |
2478 | \r | |
2479 | /* First byte */\r | |
2480 | *p = (sign << 7) | (e >> 4);\r | |
2481 | p += incr;\r | |
2482 | \r | |
2483 | /* Second byte */\r | |
2484 | *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));\r | |
2485 | p += incr;\r | |
2486 | \r | |
2487 | /* Third byte */\r | |
2488 | *p = (fhi >> 16) & 0xFF;\r | |
2489 | p += incr;\r | |
2490 | \r | |
2491 | /* Fourth byte */\r | |
2492 | *p = (fhi >> 8) & 0xFF;\r | |
2493 | p += incr;\r | |
2494 | \r | |
2495 | /* Fifth byte */\r | |
2496 | *p = fhi & 0xFF;\r | |
2497 | p += incr;\r | |
2498 | \r | |
2499 | /* Sixth byte */\r | |
2500 | *p = (flo >> 16) & 0xFF;\r | |
2501 | p += incr;\r | |
2502 | \r | |
2503 | /* Seventh byte */\r | |
2504 | *p = (flo >> 8) & 0xFF;\r | |
2505 | p += incr;\r | |
2506 | \r | |
2507 | /* Eighth byte */\r | |
2508 | *p = flo & 0xFF;\r | |
2509 | /* p += incr; Unneeded (for now) */\r | |
2510 | \r | |
2511 | /* Done */\r | |
2512 | return 0;\r | |
2513 | \r | |
2514 | Overflow:\r | |
2515 | PyErr_SetString(PyExc_OverflowError,\r | |
2516 | "float too large to pack with d format");\r | |
2517 | return -1;\r | |
2518 | }\r | |
2519 | else {\r | |
2520 | const char *s = (char*)&x;\r | |
2521 | int i, incr = 1;\r | |
2522 | \r | |
2523 | if ((double_format == ieee_little_endian_format && !le)\r | |
2524 | || (double_format == ieee_big_endian_format && le)) {\r | |
2525 | p += 7;\r | |
2526 | incr = -1;\r | |
2527 | }\r | |
2528 | \r | |
2529 | for (i = 0; i < 8; i++) {\r | |
2530 | *p = *s++;\r | |
2531 | p += incr;\r | |
2532 | }\r | |
2533 | return 0;\r | |
2534 | }\r | |
2535 | }\r | |
2536 | \r | |
2537 | double\r | |
2538 | _PyFloat_Unpack4(const unsigned char *p, int le)\r | |
2539 | {\r | |
2540 | if (float_format == unknown_format) {\r | |
2541 | unsigned char sign;\r | |
2542 | int e;\r | |
2543 | unsigned int f;\r | |
2544 | double x;\r | |
2545 | int incr = 1;\r | |
2546 | \r | |
2547 | if (le) {\r | |
2548 | p += 3;\r | |
2549 | incr = -1;\r | |
2550 | }\r | |
2551 | \r | |
2552 | /* First byte */\r | |
2553 | sign = (*p >> 7) & 1;\r | |
2554 | e = (*p & 0x7F) << 1;\r | |
2555 | p += incr;\r | |
2556 | \r | |
2557 | /* Second byte */\r | |
2558 | e |= (*p >> 7) & 1;\r | |
2559 | f = (*p & 0x7F) << 16;\r | |
2560 | p += incr;\r | |
2561 | \r | |
2562 | if (e == 255) {\r | |
2563 | PyErr_SetString(\r | |
2564 | PyExc_ValueError,\r | |
2565 | "can't unpack IEEE 754 special value "\r | |
2566 | "on non-IEEE platform");\r | |
2567 | return -1;\r | |
2568 | }\r | |
2569 | \r | |
2570 | /* Third byte */\r | |
2571 | f |= *p << 8;\r | |
2572 | p += incr;\r | |
2573 | \r | |
2574 | /* Fourth byte */\r | |
2575 | f |= *p;\r | |
2576 | \r | |
2577 | x = (double)f / 8388608.0;\r | |
2578 | \r | |
2579 | /* XXX This sadly ignores Inf/NaN issues */\r | |
2580 | if (e == 0)\r | |
2581 | e = -126;\r | |
2582 | else {\r | |
2583 | x += 1.0;\r | |
2584 | e -= 127;\r | |
2585 | }\r | |
2586 | x = ldexp(x, e);\r | |
2587 | \r | |
2588 | if (sign)\r | |
2589 | x = -x;\r | |
2590 | \r | |
2591 | return x;\r | |
2592 | }\r | |
2593 | else {\r | |
2594 | float x;\r | |
2595 | \r | |
2596 | if ((float_format == ieee_little_endian_format && !le)\r | |
2597 | || (float_format == ieee_big_endian_format && le)) {\r | |
2598 | char buf[4];\r | |
2599 | char *d = &buf[3];\r | |
2600 | int i;\r | |
2601 | \r | |
2602 | for (i = 0; i < 4; i++) {\r | |
2603 | *d-- = *p++;\r | |
2604 | }\r | |
2605 | memcpy(&x, buf, 4);\r | |
2606 | }\r | |
2607 | else {\r | |
2608 | memcpy(&x, p, 4);\r | |
2609 | }\r | |
2610 | \r | |
2611 | return x;\r | |
2612 | }\r | |
2613 | }\r | |
2614 | \r | |
2615 | double\r | |
2616 | _PyFloat_Unpack8(const unsigned char *p, int le)\r | |
2617 | {\r | |
2618 | if (double_format == unknown_format) {\r | |
2619 | unsigned char sign;\r | |
2620 | int e;\r | |
2621 | unsigned int fhi, flo;\r | |
2622 | double x;\r | |
2623 | int incr = 1;\r | |
2624 | \r | |
2625 | if (le) {\r | |
2626 | p += 7;\r | |
2627 | incr = -1;\r | |
2628 | }\r | |
2629 | \r | |
2630 | /* First byte */\r | |
2631 | sign = (*p >> 7) & 1;\r | |
2632 | e = (*p & 0x7F) << 4;\r | |
2633 | \r | |
2634 | p += incr;\r | |
2635 | \r | |
2636 | /* Second byte */\r | |
2637 | e |= (*p >> 4) & 0xF;\r | |
2638 | fhi = (*p & 0xF) << 24;\r | |
2639 | p += incr;\r | |
2640 | \r | |
2641 | if (e == 2047) {\r | |
2642 | PyErr_SetString(\r | |
2643 | PyExc_ValueError,\r | |
2644 | "can't unpack IEEE 754 special value "\r | |
2645 | "on non-IEEE platform");\r | |
2646 | return -1.0;\r | |
2647 | }\r | |
2648 | \r | |
2649 | /* Third byte */\r | |
2650 | fhi |= *p << 16;\r | |
2651 | p += incr;\r | |
2652 | \r | |
2653 | /* Fourth byte */\r | |
2654 | fhi |= *p << 8;\r | |
2655 | p += incr;\r | |
2656 | \r | |
2657 | /* Fifth byte */\r | |
2658 | fhi |= *p;\r | |
2659 | p += incr;\r | |
2660 | \r | |
2661 | /* Sixth byte */\r | |
2662 | flo = *p << 16;\r | |
2663 | p += incr;\r | |
2664 | \r | |
2665 | /* Seventh byte */\r | |
2666 | flo |= *p << 8;\r | |
2667 | p += incr;\r | |
2668 | \r | |
2669 | /* Eighth byte */\r | |
2670 | flo |= *p;\r | |
2671 | \r | |
2672 | x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */\r | |
2673 | x /= 268435456.0; /* 2**28 */\r | |
2674 | \r | |
2675 | if (e == 0)\r | |
2676 | e = -1022;\r | |
2677 | else {\r | |
2678 | x += 1.0;\r | |
2679 | e -= 1023;\r | |
2680 | }\r | |
2681 | x = ldexp(x, e);\r | |
2682 | \r | |
2683 | if (sign)\r | |
2684 | x = -x;\r | |
2685 | \r | |
2686 | return x;\r | |
2687 | }\r | |
2688 | else {\r | |
2689 | double x;\r | |
2690 | \r | |
2691 | if ((double_format == ieee_little_endian_format && !le)\r | |
2692 | || (double_format == ieee_big_endian_format && le)) {\r | |
2693 | char buf[8];\r | |
2694 | char *d = &buf[7];\r | |
2695 | int i;\r | |
2696 | \r | |
2697 | for (i = 0; i < 8; i++) {\r | |
2698 | *d-- = *p++;\r | |
2699 | }\r | |
2700 | memcpy(&x, buf, 8);\r | |
2701 | }\r | |
2702 | else {\r | |
2703 | memcpy(&x, p, 8);\r | |
2704 | }\r | |
2705 | \r | |
2706 | return x;\r | |
2707 | }\r | |
2708 | }\r |