/src/cpython/Objects/floatobject.c
Line | Count | Source |
1 | | /* Float object implementation */ |
2 | | |
3 | | /* XXX There should be overflow checks here, but it's hard to check |
4 | | for any kind of float exception without losing portability. */ |
5 | | |
6 | | #include "Python.h" |
7 | | #include "pycore_abstract.h" // _PyNumber_Index() |
8 | | #include "pycore_dtoa.h" // _Py_dg_dtoa() |
9 | | #include "pycore_floatobject.h" // _PyFloat_FormatAdvancedWriter() |
10 | | #include "pycore_freelist.h" // _Py_FREELIST_FREE(), _Py_FREELIST_POP() |
11 | | #include "pycore_initconfig.h" // _PyStatus_OK() |
12 | | #include "pycore_long.h" // _PyLong_GetOne() |
13 | | #include "pycore_modsupport.h" // _PyArg_NoKwnames() |
14 | | #include "pycore_object.h" // _PyObject_Init(), _PyDebugAllocatorStats() |
15 | | #include "pycore_pymath.h" // _PY_SHORT_FLOAT_REPR |
16 | | #include "pycore_pystate.h" // _PyInterpreterState_GET() |
17 | | #include "pycore_stackref.h" // PyStackRef_AsPyObjectBorrow() |
18 | | #include "pycore_structseq.h" // _PyStructSequence_FiniBuiltin() |
19 | | |
20 | | #include <float.h> // DBL_MAX |
21 | | #include <stdlib.h> // strtol() |
22 | | |
23 | | /*[clinic input] |
24 | | class float "PyObject *" "&PyFloat_Type" |
25 | | [clinic start generated code]*/ |
26 | | /*[clinic end generated code: output=da39a3ee5e6b4b0d input=dd0003f68f144284]*/ |
27 | | |
28 | | #include "clinic/floatobject.c.h" |
29 | | |
30 | | |
31 | | double |
32 | | PyFloat_GetMax(void) |
33 | 0 | { |
34 | 0 | return DBL_MAX; |
35 | 0 | } |
36 | | |
37 | | double |
38 | | PyFloat_GetMin(void) |
39 | 0 | { |
40 | 0 | return DBL_MIN; |
41 | 0 | } |
42 | | |
43 | | static PyTypeObject FloatInfoType; |
44 | | |
45 | | PyDoc_STRVAR(floatinfo__doc__, |
46 | | "sys.float_info\n\ |
47 | | \n\ |
48 | | A named tuple holding information about the float type. It contains low level\n\ |
49 | | information about the precision and internal representation. Please study\n\ |
50 | | your system's :file:`float.h` for more information."); |
51 | | |
52 | | static PyStructSequence_Field floatinfo_fields[] = { |
53 | | {"max", "DBL_MAX -- maximum representable finite float"}, |
54 | | {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) " |
55 | | "is representable"}, |
56 | | {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e " |
57 | | "is representable"}, |
58 | | {"min", "DBL_MIN -- Minimum positive normalized float"}, |
59 | | {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) " |
60 | | "is a normalized float"}, |
61 | | {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is " |
62 | | "a normalized float"}, |
63 | | {"dig", "DBL_DIG -- maximum number of decimal digits that " |
64 | | "can be faithfully represented in a float"}, |
65 | | {"mant_dig", "DBL_MANT_DIG -- mantissa digits"}, |
66 | | {"epsilon", "DBL_EPSILON -- Difference between 1 and the next " |
67 | | "representable float"}, |
68 | | {"radix", "FLT_RADIX -- radix of exponent"}, |
69 | | {"rounds", "FLT_ROUNDS -- rounding mode used for arithmetic " |
70 | | "operations"}, |
71 | | {0} |
72 | | }; |
73 | | |
74 | | static PyStructSequence_Desc floatinfo_desc = { |
75 | | "sys.float_info", /* name */ |
76 | | floatinfo__doc__, /* doc */ |
77 | | floatinfo_fields, /* fields */ |
78 | | 11 |
79 | | }; |
80 | | |
81 | | PyObject * |
82 | | PyFloat_GetInfo(void) |
83 | 36 | { |
84 | 36 | PyObject* floatinfo; |
85 | 36 | int pos = 0; |
86 | | |
87 | 36 | floatinfo = PyStructSequence_New(&FloatInfoType); |
88 | 36 | if (floatinfo == NULL) { |
89 | 0 | return NULL; |
90 | 0 | } |
91 | | |
92 | 36 | #define SetFlag(CALL) \ |
93 | 396 | do { \ |
94 | 396 | PyObject *flag = (CALL); \ |
95 | 396 | if (flag == NULL) { \ |
96 | 0 | Py_CLEAR(floatinfo); \ |
97 | 0 | return NULL; \ |
98 | 0 | } \ |
99 | 396 | PyStructSequence_SET_ITEM(floatinfo, pos++, flag); \ |
100 | 396 | } while (0) |
101 | | |
102 | 288 | #define SetIntFlag(FLAG) SetFlag(PyLong_FromLong((FLAG))) |
103 | 108 | #define SetDblFlag(FLAG) SetFlag(PyFloat_FromDouble((FLAG))) |
104 | | |
105 | 36 | SetDblFlag(DBL_MAX); |
106 | 36 | SetIntFlag(DBL_MAX_EXP); |
107 | 36 | SetIntFlag(DBL_MAX_10_EXP); |
108 | 36 | SetDblFlag(DBL_MIN); |
109 | 36 | SetIntFlag(DBL_MIN_EXP); |
110 | 36 | SetIntFlag(DBL_MIN_10_EXP); |
111 | 36 | SetIntFlag(DBL_DIG); |
112 | 36 | SetIntFlag(DBL_MANT_DIG); |
113 | 36 | SetDblFlag(DBL_EPSILON); |
114 | 36 | SetIntFlag(FLT_RADIX); |
115 | 36 | SetIntFlag(FLT_ROUNDS); |
116 | 36 | #undef SetIntFlag |
117 | 36 | #undef SetDblFlag |
118 | 36 | #undef SetFlag |
119 | | |
120 | 36 | return floatinfo; |
121 | 36 | } |
122 | | |
123 | | PyObject * |
124 | | PyFloat_FromDouble(double fval) |
125 | 7.64M | { |
126 | 7.64M | PyFloatObject *op = _Py_FREELIST_POP(PyFloatObject, floats); |
127 | 7.64M | if (op == NULL) { |
128 | 1.31M | op = PyObject_Malloc(sizeof(PyFloatObject)); |
129 | 1.31M | if (!op) { |
130 | 0 | return PyErr_NoMemory(); |
131 | 0 | } |
132 | 1.31M | _PyObject_Init((PyObject*)op, &PyFloat_Type); |
133 | 1.31M | } |
134 | 7.64M | op->ob_fval = fval; |
135 | 7.64M | return (PyObject *) op; |
136 | 7.64M | } |
137 | | |
138 | | static PyObject * |
139 | | float_from_string_inner(const char *s, Py_ssize_t len, void *obj) |
140 | 1.07M | { |
141 | 1.07M | double x; |
142 | 1.07M | const char *end; |
143 | 1.07M | const char *last = s + len; |
144 | | /* strip leading whitespace */ |
145 | 1.07M | while (s < last && Py_ISSPACE(*s)) { |
146 | 0 | s++; |
147 | 0 | } |
148 | 1.07M | if (s == last) { |
149 | 0 | PyErr_Format(PyExc_ValueError, |
150 | 0 | "could not convert string to float: " |
151 | 0 | "%R", obj); |
152 | 0 | return NULL; |
153 | 0 | } |
154 | | |
155 | | /* strip trailing whitespace */ |
156 | 1.07M | while (s < last - 1 && Py_ISSPACE(last[-1])) { |
157 | 0 | last--; |
158 | 0 | } |
159 | | |
160 | | /* We don't care about overflow or underflow. If the platform |
161 | | * supports them, infinities and signed zeroes (on underflow) are |
162 | | * fine. */ |
163 | 1.07M | x = PyOS_string_to_double(s, (char **)&end, NULL); |
164 | 1.07M | if (end != last) { |
165 | 0 | PyErr_Format(PyExc_ValueError, |
166 | 0 | "could not convert string to float: " |
167 | 0 | "%R", obj); |
168 | 0 | return NULL; |
169 | 0 | } |
170 | 1.07M | else if (x == -1.0 && PyErr_Occurred()) { |
171 | 0 | return NULL; |
172 | 0 | } |
173 | 1.07M | else { |
174 | 1.07M | return PyFloat_FromDouble(x); |
175 | 1.07M | } |
176 | 1.07M | } |
177 | | |
178 | | PyObject * |
179 | | PyFloat_FromString(PyObject *v) |
180 | 1.07M | { |
181 | 1.07M | const char *s; |
182 | 1.07M | PyObject *s_buffer = NULL; |
183 | 1.07M | Py_ssize_t len; |
184 | 1.07M | Py_buffer view = {NULL, NULL}; |
185 | 1.07M | PyObject *result = NULL; |
186 | | |
187 | 1.07M | if (PyUnicode_Check(v)) { |
188 | 497k | s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v); |
189 | 497k | if (s_buffer == NULL) |
190 | 0 | return NULL; |
191 | 497k | assert(PyUnicode_IS_ASCII(s_buffer)); |
192 | | /* Simply get a pointer to existing ASCII characters. */ |
193 | 497k | s = PyUnicode_AsUTF8AndSize(s_buffer, &len); |
194 | 497k | assert(s != NULL); |
195 | 497k | } |
196 | 580k | else if (PyBytes_Check(v)) { |
197 | 580k | s = PyBytes_AS_STRING(v); |
198 | 580k | len = PyBytes_GET_SIZE(v); |
199 | 580k | } |
200 | 0 | else if (PyByteArray_Check(v)) { |
201 | 0 | s = PyByteArray_AS_STRING(v); |
202 | 0 | len = PyByteArray_GET_SIZE(v); |
203 | 0 | } |
204 | 0 | else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) { |
205 | 0 | s = (const char *)view.buf; |
206 | 0 | len = view.len; |
207 | | /* Copy to NUL-terminated buffer. */ |
208 | 0 | s_buffer = PyBytes_FromStringAndSize(s, len); |
209 | 0 | if (s_buffer == NULL) { |
210 | 0 | PyBuffer_Release(&view); |
211 | 0 | return NULL; |
212 | 0 | } |
213 | 0 | s = PyBytes_AS_STRING(s_buffer); |
214 | 0 | } |
215 | 0 | else { |
216 | 0 | PyErr_Format(PyExc_TypeError, |
217 | 0 | "float() argument must be a string or a real number, not '%.200s'", |
218 | 0 | Py_TYPE(v)->tp_name); |
219 | 0 | return NULL; |
220 | 0 | } |
221 | 1.07M | result = _Py_string_to_number_with_underscores(s, len, "float", v, v, |
222 | 1.07M | float_from_string_inner); |
223 | 1.07M | PyBuffer_Release(&view); |
224 | 1.07M | Py_XDECREF(s_buffer); |
225 | 1.07M | return result; |
226 | 1.07M | } |
227 | | |
228 | | void |
229 | | _PyFloat_ExactDealloc(PyObject *obj) |
230 | 7.63M | { |
231 | 7.63M | assert(PyFloat_CheckExact(obj)); |
232 | 7.63M | _Py_FREELIST_FREE(floats, obj, PyObject_Free); |
233 | 7.63M | } |
234 | | |
235 | | static void |
236 | | float_dealloc(PyObject *op) |
237 | 7.24M | { |
238 | 7.24M | assert(PyFloat_Check(op)); |
239 | 7.24M | if (PyFloat_CheckExact(op)) |
240 | 7.24M | _PyFloat_ExactDealloc(op); |
241 | 0 | else |
242 | 0 | Py_TYPE(op)->tp_free(op); |
243 | 7.24M | } |
244 | | |
245 | | double |
246 | | PyFloat_AsDouble(PyObject *op) |
247 | 658 | { |
248 | 658 | PyNumberMethods *nb; |
249 | 658 | PyObject *res; |
250 | 658 | double val; |
251 | | |
252 | 658 | if (op == NULL) { |
253 | 0 | PyErr_BadArgument(); |
254 | 0 | return -1; |
255 | 0 | } |
256 | | |
257 | 658 | if (PyFloat_Check(op)) { |
258 | 654 | return PyFloat_AS_DOUBLE(op); |
259 | 654 | } |
260 | | |
261 | 4 | nb = Py_TYPE(op)->tp_as_number; |
262 | 4 | if (nb == NULL || nb->nb_float == NULL) { |
263 | 0 | if (nb && nb->nb_index) { |
264 | 0 | PyObject *res = _PyNumber_Index(op); |
265 | 0 | if (!res) { |
266 | 0 | return -1; |
267 | 0 | } |
268 | 0 | double val = PyLong_AsDouble(res); |
269 | 0 | Py_DECREF(res); |
270 | 0 | return val; |
271 | 0 | } |
272 | 0 | PyErr_Format(PyExc_TypeError, "must be real number, not %.50s", |
273 | 0 | Py_TYPE(op)->tp_name); |
274 | 0 | return -1; |
275 | 0 | } |
276 | | |
277 | 4 | res = (*nb->nb_float) (op); |
278 | 4 | if (res == NULL) { |
279 | 0 | return -1; |
280 | 0 | } |
281 | 4 | if (!PyFloat_CheckExact(res)) { |
282 | 0 | if (!PyFloat_Check(res)) { |
283 | 0 | PyErr_Format(PyExc_TypeError, |
284 | 0 | "%T.__float__() must return a float, not %T", |
285 | 0 | op, res); |
286 | 0 | Py_DECREF(res); |
287 | 0 | return -1; |
288 | 0 | } |
289 | 0 | if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, |
290 | 0 | "%T.__float__() must return a float, not %T. " |
291 | 0 | "The ability to return an instance of a strict subclass of float " |
292 | 0 | "is deprecated, and may be removed in a future version of Python.", |
293 | 0 | op, res)) { |
294 | 0 | Py_DECREF(res); |
295 | 0 | return -1; |
296 | 0 | } |
297 | 0 | } |
298 | | |
299 | 4 | val = PyFloat_AS_DOUBLE(res); |
300 | 4 | Py_DECREF(res); |
301 | 4 | return val; |
302 | 4 | } |
303 | | |
304 | | /* Macro and helper that convert PyObject obj to a C double and store |
305 | | the value in dbl. If conversion to double raises an exception, obj is |
306 | | set to NULL, and the function invoking this macro returns NULL. If |
307 | | obj is not of float or int type, Py_NotImplemented is incref'ed, |
308 | | stored in obj, and returned from the function invoking this macro. |
309 | | */ |
310 | | #define CONVERT_TO_DOUBLE(obj, dbl) \ |
311 | 143k | if (PyFloat_Check(obj)) \ |
312 | 143k | dbl = PyFloat_AS_DOUBLE(obj); \ |
313 | 143k | else if (_Py_convert_int_to_double(&(obj), &(dbl)) < 0) \ |
314 | 71.0k | return obj; |
315 | | |
316 | | /* Methods */ |
317 | | |
318 | | int |
319 | | _Py_convert_int_to_double(PyObject **v, double *dbl) |
320 | 71.0k | { |
321 | 71.0k | PyObject *obj = *v; |
322 | | |
323 | 71.0k | if (PyLong_Check(obj)) { |
324 | 71.0k | *dbl = PyLong_AsDouble(obj); |
325 | 71.0k | if (*dbl == -1.0 && PyErr_Occurred()) { |
326 | 0 | *v = NULL; |
327 | 0 | return -1; |
328 | 0 | } |
329 | 71.0k | } |
330 | 0 | else { |
331 | 0 | *v = Py_NewRef(Py_NotImplemented); |
332 | 0 | return -1; |
333 | 0 | } |
334 | 71.0k | return 0; |
335 | 71.0k | } |
336 | | |
337 | | static PyObject * |
338 | | float_repr(PyObject *op) |
339 | 50.0k | { |
340 | 50.0k | PyFloatObject *v = _PyFloat_CAST(op); |
341 | 50.0k | PyObject *result; |
342 | 50.0k | char *buf; |
343 | | |
344 | 50.0k | buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v), |
345 | 50.0k | 'r', 0, |
346 | 50.0k | Py_DTSF_ADD_DOT_0, |
347 | 50.0k | NULL); |
348 | 50.0k | if (!buf) |
349 | 0 | return PyErr_NoMemory(); |
350 | 50.0k | result = _PyUnicode_FromASCII(buf, strlen(buf)); |
351 | 50.0k | PyMem_Free(buf); |
352 | 50.0k | return result; |
353 | 50.0k | } |
354 | | |
355 | | /* Comparison is pretty much a nightmare. When comparing float to float, |
356 | | * we do it as straightforwardly (and long-windedly) as conceivable, so |
357 | | * that, e.g., Python x == y delivers the same result as the platform |
358 | | * C x == y when x and/or y is a NaN. |
359 | | * When mixing float with an integer type, there's no good *uniform* approach. |
360 | | * Converting the double to an integer obviously doesn't work, since we |
361 | | * may lose info from fractional bits. Converting the integer to a double |
362 | | * also has two failure modes: (1) an int may trigger overflow (too |
363 | | * large to fit in the dynamic range of a C double); (2) even a C long may have |
364 | | * more bits than fit in a C double (e.g., on a 64-bit box long may have |
365 | | * 63 bits of precision, but a C double probably has only 53), and then |
366 | | * we can falsely claim equality when low-order integer bits are lost by |
367 | | * coercion to double. So this part is painful too. |
368 | | */ |
369 | | |
370 | | static PyObject* |
371 | | float_richcompare(PyObject *v, PyObject *w, int op) |
372 | 8.84M | { |
373 | 8.84M | double i, j; |
374 | 8.84M | int r = 0; |
375 | | |
376 | 8.84M | assert(PyFloat_Check(v)); |
377 | 8.84M | i = PyFloat_AS_DOUBLE(v); |
378 | | |
379 | | /* Switch on the type of w. Set i and j to doubles to be compared, |
380 | | * and op to the richcomp to use. |
381 | | */ |
382 | 8.84M | if (PyFloat_Check(w)) |
383 | 3.97M | j = PyFloat_AS_DOUBLE(w); |
384 | | |
385 | 4.86M | else if (!isfinite(i)) { |
386 | 49.2k | if (PyLong_Check(w)) |
387 | | /* If i is an infinity, its magnitude exceeds any |
388 | | * finite integer, so it doesn't matter which int we |
389 | | * compare i with. If i is a NaN, similarly. |
390 | | */ |
391 | 49.2k | j = 0.0; |
392 | 0 | else |
393 | 0 | goto Unimplemented; |
394 | 49.2k | } |
395 | | |
396 | 4.81M | else if (PyLong_Check(w)) { |
397 | 4.81M | int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1; |
398 | 4.81M | int wsign; |
399 | 4.81M | int exponent; |
400 | | |
401 | 4.81M | (void)PyLong_GetSign(w, &wsign); |
402 | 4.81M | if (vsign != wsign) { |
403 | | /* Magnitudes are irrelevant -- the signs alone |
404 | | * determine the outcome. |
405 | | */ |
406 | 2.46M | i = (double)vsign; |
407 | 2.46M | j = (double)wsign; |
408 | 2.46M | goto Compare; |
409 | 2.46M | } |
410 | | /* The signs are the same. */ |
411 | | /* Convert w to a double if it fits. In particular, 0 fits. */ |
412 | 2.34M | int64_t nbits64 = _PyLong_NumBits(w); |
413 | 2.34M | assert(nbits64 >= 0); |
414 | 2.34M | assert(!PyErr_Occurred()); |
415 | 2.34M | if (nbits64 > DBL_MAX_EXP) { |
416 | | /* This Python integer is larger than any finite C double. |
417 | | * Replace with little doubles |
418 | | * that give the same outcome -- w is so large that |
419 | | * its magnitude must exceed the magnitude of any |
420 | | * finite float. |
421 | | */ |
422 | 0 | i = (double)vsign; |
423 | 0 | assert(wsign != 0); |
424 | 0 | j = wsign * 2.0; |
425 | 0 | goto Compare; |
426 | 0 | } |
427 | 2.34M | int nbits = (int)nbits64; |
428 | 2.34M | if (nbits <= 48) { |
429 | 2.34M | j = PyLong_AsDouble(w); |
430 | | /* It's impossible that <= 48 bits overflowed. */ |
431 | 2.34M | assert(j != -1.0 || ! PyErr_Occurred()); |
432 | 2.34M | goto Compare; |
433 | 2.34M | } |
434 | 2.34M | assert(wsign != 0); /* else nbits was 0 */ |
435 | 0 | assert(vsign != 0); /* if vsign were 0, then since wsign is |
436 | | * not 0, we would have taken the |
437 | | * vsign != wsign branch at the start */ |
438 | 0 | (void) frexp(i, &exponent); |
439 | | /* exponent is the # of bits in v before the radix point; |
440 | | * we know that nbits (the # of bits in w) > 48 at this point |
441 | | */ |
442 | 0 | if (exponent < nbits) { |
443 | 0 | j = i; |
444 | 0 | i = 0.0; |
445 | 0 | goto Compare; |
446 | 0 | } |
447 | 0 | if (exponent > nbits) { |
448 | 0 | j = 0.0; |
449 | 0 | goto Compare; |
450 | 0 | } |
451 | | /* v and w have the same number of bits before the radix |
452 | | * point. Construct an int from the integer part of v and |
453 | | * update op if necessary, so comparing two ints has the same outcome. |
454 | | */ |
455 | 0 | { |
456 | 0 | double fracpart; |
457 | 0 | double intpart; |
458 | 0 | PyObject *result = NULL; |
459 | 0 | PyObject *vv = NULL; |
460 | |
|
461 | 0 | fracpart = modf(i, &intpart); |
462 | 0 | if (fracpart != 0.0) { |
463 | 0 | switch (op) { |
464 | | /* Non-integer float never equals to an int. */ |
465 | 0 | case Py_EQ: |
466 | 0 | Py_RETURN_FALSE; |
467 | 0 | case Py_NE: |
468 | 0 | Py_RETURN_TRUE; |
469 | | /* For non-integer float, v <= w <=> v < w. |
470 | | * If v > 0: trunc(v) < v < trunc(v) + 1 |
471 | | * v < w => trunc(v) < w |
472 | | * trunc(v) < w => trunc(v) + 1 <= w => v < w |
473 | | * If v < 0: trunc(v) - 1 < v < trunc(v) |
474 | | * v < w => trunc(v) - 1 < w => trunc(v) <= w |
475 | | * trunc(v) <= w => v < w |
476 | | */ |
477 | 0 | case Py_LT: |
478 | 0 | case Py_LE: |
479 | 0 | op = vsign > 0 ? Py_LT : Py_LE; |
480 | 0 | break; |
481 | | /* The same as above, but with opposite directions. */ |
482 | 0 | case Py_GT: |
483 | 0 | case Py_GE: |
484 | 0 | op = vsign > 0 ? Py_GE : Py_GT; |
485 | 0 | break; |
486 | 0 | } |
487 | 0 | } |
488 | | |
489 | 0 | vv = PyLong_FromDouble(intpart); |
490 | 0 | if (vv == NULL) |
491 | 0 | goto Error; |
492 | | |
493 | 0 | r = PyObject_RichCompareBool(vv, w, op); |
494 | 0 | if (r < 0) |
495 | 0 | goto Error; |
496 | 0 | result = PyBool_FromLong(r); |
497 | 0 | Error: |
498 | 0 | Py_XDECREF(vv); |
499 | 0 | return result; |
500 | 0 | } |
501 | 0 | } /* else if (PyLong_Check(w)) */ |
502 | | |
503 | 0 | else /* w isn't float or int */ |
504 | 0 | goto Unimplemented; |
505 | | |
506 | 8.84M | Compare: |
507 | 8.84M | switch (op) { |
508 | 4.02M | case Py_EQ: |
509 | 4.02M | r = i == j; |
510 | 4.02M | break; |
511 | 267k | case Py_NE: |
512 | 267k | r = i != j; |
513 | 267k | break; |
514 | 2.14M | case Py_LE: |
515 | 2.14M | r = i <= j; |
516 | 2.14M | break; |
517 | 2.14M | case Py_GE: |
518 | 2.14M | r = i >= j; |
519 | 2.14M | break; |
520 | 202k | case Py_LT: |
521 | 202k | r = i < j; |
522 | 202k | break; |
523 | 49.3k | case Py_GT: |
524 | 49.3k | r = i > j; |
525 | 49.3k | break; |
526 | 8.84M | } |
527 | 8.84M | return PyBool_FromLong(r); |
528 | | |
529 | 0 | Unimplemented: |
530 | 0 | Py_RETURN_NOTIMPLEMENTED; |
531 | 8.84M | } |
532 | | |
533 | | static Py_hash_t |
534 | | float_hash(PyObject *op) |
535 | 2.18M | { |
536 | 2.18M | PyFloatObject *v = _PyFloat_CAST(op); |
537 | 2.18M | return _Py_HashDouble(op, v->ob_fval); |
538 | 2.18M | } |
539 | | |
540 | | static PyObject * |
541 | | float_add(PyObject *v, PyObject *w) |
542 | 70.7k | { |
543 | 70.7k | double a,b; |
544 | 70.7k | CONVERT_TO_DOUBLE(v, a); |
545 | 70.7k | CONVERT_TO_DOUBLE(w, b); |
546 | 70.7k | a = a + b; |
547 | 70.7k | return PyFloat_FromDouble(a); |
548 | 70.7k | } |
549 | | |
550 | | static PyObject * |
551 | | float_sub(PyObject *v, PyObject *w) |
552 | 388 | { |
553 | 388 | double a,b; |
554 | 388 | CONVERT_TO_DOUBLE(v, a); |
555 | 388 | CONVERT_TO_DOUBLE(w, b); |
556 | 388 | a = a - b; |
557 | 388 | return PyFloat_FromDouble(a); |
558 | 388 | } |
559 | | |
560 | | static PyObject * |
561 | | float_mul(PyObject *v, PyObject *w) |
562 | 227 | { |
563 | 227 | double a,b; |
564 | 227 | CONVERT_TO_DOUBLE(v, a); |
565 | 227 | CONVERT_TO_DOUBLE(w, b); |
566 | 227 | a = a * b; |
567 | 227 | return PyFloat_FromDouble(a); |
568 | 227 | } |
569 | | |
570 | | static PyObject * |
571 | | float_div(PyObject *v, PyObject *w) |
572 | 104 | { |
573 | 104 | double a,b; |
574 | 104 | CONVERT_TO_DOUBLE(v, a); |
575 | 104 | CONVERT_TO_DOUBLE(w, b); |
576 | 104 | if (b == 0.0) { |
577 | 0 | PyErr_SetString(PyExc_ZeroDivisionError, |
578 | 0 | "division by zero"); |
579 | 0 | return NULL; |
580 | 0 | } |
581 | 104 | a = a / b; |
582 | 104 | return PyFloat_FromDouble(a); |
583 | 104 | } |
584 | | |
585 | | static PyObject * |
586 | | float_rem(PyObject *v, PyObject *w) |
587 | 0 | { |
588 | 0 | double vx, wx; |
589 | 0 | double mod; |
590 | 0 | CONVERT_TO_DOUBLE(v, vx); |
591 | 0 | CONVERT_TO_DOUBLE(w, wx); |
592 | 0 | if (wx == 0.0) { |
593 | 0 | PyErr_SetString(PyExc_ZeroDivisionError, |
594 | 0 | "division by zero"); |
595 | 0 | return NULL; |
596 | 0 | } |
597 | 0 | mod = fmod(vx, wx); |
598 | 0 | if (mod) { |
599 | | /* ensure the remainder has the same sign as the denominator */ |
600 | 0 | if ((wx < 0) != (mod < 0)) { |
601 | 0 | mod += wx; |
602 | 0 | } |
603 | 0 | } |
604 | 0 | else { |
605 | | /* the remainder is zero, and in the presence of signed zeroes |
606 | | fmod returns different results across platforms; ensure |
607 | | it has the same sign as the denominator. */ |
608 | 0 | mod = copysign(0.0, wx); |
609 | 0 | } |
610 | 0 | return PyFloat_FromDouble(mod); |
611 | 0 | } |
612 | | |
613 | | static void |
614 | | _float_div_mod(double vx, double wx, double *floordiv, double *mod) |
615 | 0 | { |
616 | 0 | double div; |
617 | 0 | *mod = fmod(vx, wx); |
618 | | /* fmod is typically exact, so vx-mod is *mathematically* an |
619 | | exact multiple of wx. But this is fp arithmetic, and fp |
620 | | vx - mod is an approximation; the result is that div may |
621 | | not be an exact integral value after the division, although |
622 | | it will always be very close to one. |
623 | | */ |
624 | 0 | div = (vx - *mod) / wx; |
625 | 0 | if (*mod) { |
626 | | /* ensure the remainder has the same sign as the denominator */ |
627 | 0 | if ((wx < 0) != (*mod < 0)) { |
628 | 0 | *mod += wx; |
629 | 0 | div -= 1.0; |
630 | 0 | } |
631 | 0 | } |
632 | 0 | else { |
633 | | /* the remainder is zero, and in the presence of signed zeroes |
634 | | fmod returns different results across platforms; ensure |
635 | | it has the same sign as the denominator. */ |
636 | 0 | *mod = copysign(0.0, wx); |
637 | 0 | } |
638 | | /* snap quotient to nearest integral value */ |
639 | 0 | if (div) { |
640 | 0 | *floordiv = floor(div); |
641 | 0 | if (div - *floordiv > 0.5) { |
642 | 0 | *floordiv += 1.0; |
643 | 0 | } |
644 | 0 | } |
645 | 0 | else { |
646 | | /* div is zero - get the same sign as the true quotient */ |
647 | 0 | *floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */ |
648 | 0 | } |
649 | 0 | } |
650 | | |
651 | | static PyObject * |
652 | | float_divmod(PyObject *v, PyObject *w) |
653 | 0 | { |
654 | 0 | double vx, wx; |
655 | 0 | double mod, floordiv; |
656 | 0 | CONVERT_TO_DOUBLE(v, vx); |
657 | 0 | CONVERT_TO_DOUBLE(w, wx); |
658 | 0 | if (wx == 0.0) { |
659 | 0 | PyErr_SetString(PyExc_ZeroDivisionError, "division by zero"); |
660 | 0 | return NULL; |
661 | 0 | } |
662 | 0 | _float_div_mod(vx, wx, &floordiv, &mod); |
663 | 0 | return Py_BuildValue("(dd)", floordiv, mod); |
664 | 0 | } |
665 | | |
666 | | static PyObject * |
667 | | float_floor_div(PyObject *v, PyObject *w) |
668 | 0 | { |
669 | 0 | double vx, wx; |
670 | 0 | double mod, floordiv; |
671 | 0 | CONVERT_TO_DOUBLE(v, vx); |
672 | 0 | CONVERT_TO_DOUBLE(w, wx); |
673 | 0 | if (wx == 0.0) { |
674 | 0 | PyErr_SetString(PyExc_ZeroDivisionError, "division by zero"); |
675 | 0 | return NULL; |
676 | 0 | } |
677 | 0 | _float_div_mod(vx, wx, &floordiv, &mod); |
678 | 0 | return PyFloat_FromDouble(floordiv); |
679 | 0 | } |
680 | | |
681 | | /* determine whether x is an odd integer or not; assumes that |
682 | | x is not an infinity or nan. */ |
683 | 0 | #define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0) |
684 | | |
685 | | static PyObject * |
686 | | float_pow(PyObject *v, PyObject *w, PyObject *z) |
687 | 78 | { |
688 | 78 | double iv, iw, ix; |
689 | 78 | int negate_result = 0; |
690 | | |
691 | 78 | if ((PyObject *)z != Py_None) { |
692 | 0 | PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not " |
693 | 0 | "allowed unless all arguments are integers"); |
694 | 0 | return NULL; |
695 | 0 | } |
696 | | |
697 | 78 | CONVERT_TO_DOUBLE(v, iv); |
698 | 78 | CONVERT_TO_DOUBLE(w, iw); |
699 | | |
700 | | /* Sort out special cases here instead of relying on pow() */ |
701 | 78 | if (iw == 0) { /* v**0 is 1, even 0**0 */ |
702 | 0 | return PyFloat_FromDouble(1.0); |
703 | 0 | } |
704 | 78 | if (isnan(iv)) { /* nan**w = nan, unless w == 0 */ |
705 | 0 | return PyFloat_FromDouble(iv); |
706 | 0 | } |
707 | 78 | if (isnan(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */ |
708 | 0 | return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw); |
709 | 0 | } |
710 | 78 | if (isinf(iw)) { |
711 | | /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if |
712 | | * abs(v) > 1 (including case where v infinite) |
713 | | * |
714 | | * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if |
715 | | * abs(v) > 1 (including case where v infinite) |
716 | | */ |
717 | 0 | iv = fabs(iv); |
718 | 0 | if (iv == 1.0) |
719 | 0 | return PyFloat_FromDouble(1.0); |
720 | 0 | else if ((iw > 0.0) == (iv > 1.0)) |
721 | 0 | return PyFloat_FromDouble(fabs(iw)); /* return inf */ |
722 | 0 | else |
723 | 0 | return PyFloat_FromDouble(0.0); |
724 | 0 | } |
725 | 78 | if (isinf(iv)) { |
726 | | /* (+-inf)**w is: inf for w positive, 0 for w negative; in |
727 | | * both cases, we need to add the appropriate sign if w is |
728 | | * an odd integer. |
729 | | */ |
730 | 0 | int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw); |
731 | 0 | if (iw > 0.0) |
732 | 0 | return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv)); |
733 | 0 | else |
734 | 0 | return PyFloat_FromDouble(iw_is_odd ? |
735 | 0 | copysign(0.0, iv) : 0.0); |
736 | 0 | } |
737 | 78 | if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero |
738 | | (already dealt with above), and an error |
739 | | if w is negative. */ |
740 | 0 | int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw); |
741 | 0 | if (iw < 0.0) { |
742 | 0 | PyErr_SetString(PyExc_ZeroDivisionError, |
743 | 0 | "zero to a negative power"); |
744 | 0 | return NULL; |
745 | 0 | } |
746 | | /* use correct sign if iw is odd */ |
747 | 0 | return PyFloat_FromDouble(iw_is_odd ? iv : 0.0); |
748 | 0 | } |
749 | | |
750 | 78 | if (iv < 0.0) { |
751 | | /* Whether this is an error is a mess, and bumps into libm |
752 | | * bugs so we have to figure it out ourselves. |
753 | | */ |
754 | 0 | if (iw != floor(iw)) { |
755 | | /* Negative numbers raised to fractional powers |
756 | | * become complex. |
757 | | */ |
758 | 0 | return PyComplex_Type.tp_as_number->nb_power(v, w, z); |
759 | 0 | } |
760 | | /* iw is an exact integer, albeit perhaps a very large |
761 | | * one. Replace iv by its absolute value and remember |
762 | | * to negate the pow result if iw is odd. |
763 | | */ |
764 | 0 | iv = -iv; |
765 | 0 | negate_result = DOUBLE_IS_ODD_INTEGER(iw); |
766 | 0 | } |
767 | | |
768 | 78 | if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */ |
769 | | /* (-1) ** large_integer also ends up here. Here's an |
770 | | * extract from the comments for the previous |
771 | | * implementation explaining why this special case is |
772 | | * necessary: |
773 | | * |
774 | | * -1 raised to an exact integer should never be exceptional. |
775 | | * Alas, some libms (chiefly glibc as of early 2003) return |
776 | | * NaN and set EDOM on pow(-1, large_int) if the int doesn't |
777 | | * happen to be representable in a *C* integer. That's a |
778 | | * bug. |
779 | | */ |
780 | 0 | return PyFloat_FromDouble(negate_result ? -1.0 : 1.0); |
781 | 0 | } |
782 | | |
783 | | /* Now iv and iw are finite, iw is nonzero, and iv is |
784 | | * positive and not equal to 1.0. We finally allow |
785 | | * the platform pow to step in and do the rest. |
786 | | */ |
787 | 78 | errno = 0; |
788 | 78 | ix = pow(iv, iw); |
789 | 78 | _Py_ADJUST_ERANGE1(ix); |
790 | 78 | if (negate_result) |
791 | 0 | ix = -ix; |
792 | | |
793 | 78 | if (errno != 0) { |
794 | | /* We don't expect any errno value other than ERANGE, but |
795 | | * the range of libm bugs appears unbounded. |
796 | | */ |
797 | 0 | PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : |
798 | 0 | PyExc_ValueError); |
799 | 0 | return NULL; |
800 | 0 | } |
801 | 78 | return PyFloat_FromDouble(ix); |
802 | 78 | } |
803 | | |
804 | | #undef DOUBLE_IS_ODD_INTEGER |
805 | | |
806 | | static PyObject * |
807 | | float_neg(PyObject *op) |
808 | 3.47k | { |
809 | 3.47k | PyFloatObject *v = _PyFloat_CAST(op); |
810 | 3.47k | return PyFloat_FromDouble(-v->ob_fval); |
811 | 3.47k | } |
812 | | |
813 | | static PyObject * |
814 | | float_abs(PyObject *op) |
815 | 0 | { |
816 | 0 | PyFloatObject *v = _PyFloat_CAST(op); |
817 | 0 | return PyFloat_FromDouble(fabs(v->ob_fval)); |
818 | 0 | } |
819 | | |
820 | | static int |
821 | | float_bool(PyObject *op) |
822 | 4 | { |
823 | 4 | PyFloatObject *v = _PyFloat_CAST(op); |
824 | 4 | return v->ob_fval != 0.0; |
825 | 4 | } |
826 | | |
827 | | /*[clinic input] |
828 | | float.is_integer |
829 | | |
830 | | Return True if the float is an integer. |
831 | | [clinic start generated code]*/ |
832 | | |
833 | | static PyObject * |
834 | | float_is_integer_impl(PyObject *self) |
835 | | /*[clinic end generated code: output=7112acf95a4d31ea input=311810d3f777e10d]*/ |
836 | 0 | { |
837 | 0 | double x = PyFloat_AsDouble(self); |
838 | 0 | PyObject *o; |
839 | |
|
840 | 0 | if (x == -1.0 && PyErr_Occurred()) |
841 | 0 | return NULL; |
842 | 0 | if (!isfinite(x)) |
843 | 0 | Py_RETURN_FALSE; |
844 | 0 | errno = 0; |
845 | 0 | o = (floor(x) == x) ? Py_True : Py_False; |
846 | 0 | if (errno != 0) { |
847 | 0 | PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : |
848 | 0 | PyExc_ValueError); |
849 | 0 | return NULL; |
850 | 0 | } |
851 | 0 | return Py_NewRef(o); |
852 | 0 | } |
853 | | |
854 | | /*[clinic input] |
855 | | float.__trunc__ |
856 | | |
857 | | Return the Integral closest to x between 0 and x. |
858 | | [clinic start generated code]*/ |
859 | | |
860 | | static PyObject * |
861 | | float___trunc___impl(PyObject *self) |
862 | | /*[clinic end generated code: output=dd3e289dd4c6b538 input=591b9ba0d650fdff]*/ |
863 | 18.3k | { |
864 | 18.3k | return PyLong_FromDouble(PyFloat_AS_DOUBLE(self)); |
865 | 18.3k | } |
866 | | |
867 | | /*[clinic input] |
868 | | float.__floor__ |
869 | | |
870 | | Return the floor as an Integral. |
871 | | [clinic start generated code]*/ |
872 | | |
873 | | static PyObject * |
874 | | float___floor___impl(PyObject *self) |
875 | | /*[clinic end generated code: output=e0551dbaea8c01d1 input=77bb13eb12e268df]*/ |
876 | 0 | { |
877 | 0 | double x = PyFloat_AS_DOUBLE(self); |
878 | 0 | return PyLong_FromDouble(floor(x)); |
879 | 0 | } |
880 | | |
881 | | /*[clinic input] |
882 | | float.__ceil__ |
883 | | |
884 | | Return the ceiling as an Integral. |
885 | | [clinic start generated code]*/ |
886 | | |
887 | | static PyObject * |
888 | | float___ceil___impl(PyObject *self) |
889 | | /*[clinic end generated code: output=a2fd8858f73736f9 input=79e41ae94aa0a516]*/ |
890 | 0 | { |
891 | 0 | double x = PyFloat_AS_DOUBLE(self); |
892 | 0 | return PyLong_FromDouble(ceil(x)); |
893 | 0 | } |
894 | | |
895 | | /* double_round: rounds a finite double to the closest multiple of |
896 | | 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <= |
897 | | ndigits <= 323). Returns a Python float, or sets a Python error and |
898 | | returns NULL on failure (OverflowError and memory errors are possible). */ |
899 | | |
900 | | #if _PY_SHORT_FLOAT_REPR == 1 |
901 | | /* version of double_round that uses the correctly-rounded string<->double |
902 | | conversions from Python/dtoa.c */ |
903 | | |
904 | | static PyObject * |
905 | 0 | double_round(double x, int ndigits) { |
906 | |
|
907 | 0 | double rounded; |
908 | 0 | Py_ssize_t buflen, mybuflen=100; |
909 | 0 | char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf; |
910 | 0 | int decpt, sign; |
911 | 0 | PyObject *result = NULL; |
912 | 0 | _Py_SET_53BIT_PRECISION_HEADER; |
913 | | |
914 | | /* round to a decimal string */ |
915 | 0 | _Py_SET_53BIT_PRECISION_START; |
916 | 0 | buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end); |
917 | 0 | _Py_SET_53BIT_PRECISION_END; |
918 | 0 | if (buf == NULL) { |
919 | 0 | PyErr_NoMemory(); |
920 | 0 | return NULL; |
921 | 0 | } |
922 | | |
923 | | /* Get new buffer if shortbuf is too small. Space needed <= buf_end - |
924 | | buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */ |
925 | 0 | buflen = buf_end - buf; |
926 | 0 | if (buflen + 8 > mybuflen) { |
927 | 0 | mybuflen = buflen+8; |
928 | 0 | mybuf = (char *)PyMem_Malloc(mybuflen); |
929 | 0 | if (mybuf == NULL) { |
930 | 0 | PyErr_NoMemory(); |
931 | 0 | goto exit; |
932 | 0 | } |
933 | 0 | } |
934 | | /* copy buf to mybuf, adding exponent, sign and leading 0 */ |
935 | 0 | PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""), |
936 | 0 | buf, decpt - (int)buflen); |
937 | | |
938 | | /* and convert the resulting string back to a double */ |
939 | 0 | errno = 0; |
940 | 0 | _Py_SET_53BIT_PRECISION_START; |
941 | 0 | rounded = _Py_dg_strtod(mybuf, NULL); |
942 | 0 | _Py_SET_53BIT_PRECISION_END; |
943 | 0 | if (errno == ERANGE && fabs(rounded) >= 1.) |
944 | 0 | PyErr_SetString(PyExc_OverflowError, |
945 | 0 | "rounded value too large to represent"); |
946 | 0 | else |
947 | 0 | result = PyFloat_FromDouble(rounded); |
948 | | |
949 | | /* done computing value; now clean up */ |
950 | 0 | if (mybuf != shortbuf) |
951 | 0 | PyMem_Free(mybuf); |
952 | 0 | exit: |
953 | 0 | _Py_dg_freedtoa(buf); |
954 | 0 | return result; |
955 | 0 | } |
956 | | |
957 | | #else // _PY_SHORT_FLOAT_REPR == 0 |
958 | | |
959 | | /* fallback version, to be used when correctly rounded binary<->decimal |
960 | | conversions aren't available */ |
961 | | |
962 | | static PyObject * |
963 | | double_round(double x, int ndigits) { |
964 | | double pow1, pow2, y, z; |
965 | | if (ndigits >= 0) { |
966 | | if (ndigits > 22) { |
967 | | /* pow1 and pow2 are each safe from overflow, but |
968 | | pow1*pow2 ~= pow(10.0, ndigits) might overflow */ |
969 | | pow1 = pow(10.0, (double)(ndigits-22)); |
970 | | pow2 = 1e22; |
971 | | } |
972 | | else { |
973 | | pow1 = pow(10.0, (double)ndigits); |
974 | | pow2 = 1.0; |
975 | | } |
976 | | y = (x*pow1)*pow2; |
977 | | /* if y overflows, then rounded value is exactly x */ |
978 | | if (!isfinite(y)) |
979 | | return PyFloat_FromDouble(x); |
980 | | } |
981 | | else { |
982 | | pow1 = pow(10.0, (double)-ndigits); |
983 | | pow2 = 1.0; /* unused; silences a gcc compiler warning */ |
984 | | y = x / pow1; |
985 | | } |
986 | | |
987 | | z = round(y); |
988 | | if (fabs(y-z) == 0.5) |
989 | | /* halfway between two integers; use round-half-even */ |
990 | | z = 2.0*round(y/2.0); |
991 | | |
992 | | if (ndigits >= 0) |
993 | | z = (z / pow2) / pow1; |
994 | | else |
995 | | z *= pow1; |
996 | | |
997 | | /* if computation resulted in overflow, raise OverflowError */ |
998 | | if (!isfinite(z)) { |
999 | | PyErr_SetString(PyExc_OverflowError, |
1000 | | "overflow occurred during round"); |
1001 | | return NULL; |
1002 | | } |
1003 | | |
1004 | | return PyFloat_FromDouble(z); |
1005 | | } |
1006 | | |
1007 | | #endif // _PY_SHORT_FLOAT_REPR == 0 |
1008 | | |
1009 | | /* round a Python float v to the closest multiple of 10**-ndigits */ |
1010 | | |
1011 | | /*[clinic input] |
1012 | | float.__round__ |
1013 | | |
1014 | | ndigits as o_ndigits: object = None |
1015 | | / |
1016 | | |
1017 | | Return the Integral closest to x, rounding half toward even. |
1018 | | |
1019 | | When an argument is passed, work like built-in round(x, ndigits). |
1020 | | [clinic start generated code]*/ |
1021 | | |
1022 | | static PyObject * |
1023 | | float___round___impl(PyObject *self, PyObject *o_ndigits) |
1024 | | /*[clinic end generated code: output=374c36aaa0f13980 input=fc0fe25924fbc9ed]*/ |
1025 | 0 | { |
1026 | 0 | double x, rounded; |
1027 | 0 | Py_ssize_t ndigits; |
1028 | |
|
1029 | 0 | x = PyFloat_AsDouble(self); |
1030 | 0 | if (o_ndigits == Py_None) { |
1031 | | /* single-argument round or with None ndigits: |
1032 | | * round to nearest integer */ |
1033 | 0 | rounded = round(x); |
1034 | 0 | if (fabs(x-rounded) == 0.5) |
1035 | | /* halfway case: round to even */ |
1036 | 0 | rounded = 2.0*round(x/2.0); |
1037 | 0 | return PyLong_FromDouble(rounded); |
1038 | 0 | } |
1039 | | |
1040 | | /* interpret second argument as a Py_ssize_t; clips on overflow */ |
1041 | 0 | ndigits = PyNumber_AsSsize_t(o_ndigits, NULL); |
1042 | 0 | if (ndigits == -1 && PyErr_Occurred()) |
1043 | 0 | return NULL; |
1044 | | |
1045 | | /* nans and infinities round to themselves */ |
1046 | 0 | if (!isfinite(x)) |
1047 | 0 | return PyFloat_FromDouble(x); |
1048 | | |
1049 | | /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x |
1050 | | always rounds to itself. For ndigits < NDIGITS_MIN, x always |
1051 | | rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */ |
1052 | 0 | #define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103)) |
1053 | 0 | #define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103)) |
1054 | 0 | if (ndigits > NDIGITS_MAX) |
1055 | | /* return x */ |
1056 | 0 | return PyFloat_FromDouble(x); |
1057 | 0 | else if (ndigits < NDIGITS_MIN) |
1058 | | /* return 0.0, but with sign of x */ |
1059 | 0 | return PyFloat_FromDouble(0.0*x); |
1060 | 0 | else |
1061 | | /* finite x, and ndigits is not unreasonably large */ |
1062 | 0 | return double_round(x, (int)ndigits); |
1063 | 0 | #undef NDIGITS_MAX |
1064 | 0 | #undef NDIGITS_MIN |
1065 | 0 | } |
1066 | | |
1067 | | static PyObject * |
1068 | | float_float(PyObject *v) |
1069 | 0 | { |
1070 | 0 | if (PyFloat_CheckExact(v)) { |
1071 | 0 | return Py_NewRef(v); |
1072 | 0 | } |
1073 | 0 | else { |
1074 | 0 | return PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval); |
1075 | 0 | } |
1076 | 0 | } |
1077 | | |
1078 | | /*[clinic input] |
1079 | | float.conjugate |
1080 | | |
1081 | | Return self, the complex conjugate of any float. |
1082 | | [clinic start generated code]*/ |
1083 | | |
1084 | | static PyObject * |
1085 | | float_conjugate_impl(PyObject *self) |
1086 | | /*[clinic end generated code: output=8ca292c2479194af input=82ba6f37a9ff91dd]*/ |
1087 | 0 | { |
1088 | 0 | return float_float(self); |
1089 | 0 | } |
1090 | | |
1091 | | /* turn ASCII hex characters into integer values and vice versa */ |
1092 | | |
1093 | | static char |
1094 | | char_from_hex(int x) |
1095 | 0 | { |
1096 | 0 | assert(0 <= x && x < 16); |
1097 | 0 | return Py_hexdigits[x]; |
1098 | 0 | } |
1099 | | |
1100 | | /* This table maps characters to their hexadecimal values, only |
1101 | | * works with encodings whose lower half is ASCII (like UTF-8). |
1102 | | * '0' maps to 0, ..., '9' maps to 9. |
1103 | | * 'a' and 'A' map to 10, ..., 'f' and 'F' map to 15. |
1104 | | * All other indices map to -1. |
1105 | | */ |
1106 | | static const int |
1107 | | _CHAR_TO_HEX[256] = { |
1108 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
1109 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
1110 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
1111 | | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, |
1112 | | -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
1113 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
1114 | | -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
1115 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
1116 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
1117 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
1118 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
1119 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
1120 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
1121 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
1122 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
1123 | | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, |
1124 | | }; |
1125 | | |
1126 | | /* Convert a character to its hexadecimal value, or -1 if it's not a |
1127 | | * valid hexadecimal character, only works with encodings whose lower |
1128 | | * half is ASCII (like UTF-8). |
1129 | | */ |
1130 | | static int |
1131 | 0 | hex_from_char(unsigned char c) { |
1132 | 0 | return _CHAR_TO_HEX[c]; |
1133 | 0 | } |
1134 | | |
1135 | | /* convert a float to a hexadecimal string */ |
1136 | | |
1137 | | /* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer |
1138 | | of the form 4k+1. */ |
1139 | 0 | #define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4 |
1140 | | |
1141 | | /*[clinic input] |
1142 | | float.hex |
1143 | | |
1144 | | Return a hexadecimal representation of a floating-point number. |
1145 | | |
1146 | | >>> (-0.1).hex() |
1147 | | '-0x1.999999999999ap-4' |
1148 | | >>> 3.14159.hex() |
1149 | | '0x1.921f9f01b866ep+1' |
1150 | | [clinic start generated code]*/ |
1151 | | |
1152 | | static PyObject * |
1153 | | float_hex_impl(PyObject *self) |
1154 | | /*[clinic end generated code: output=0ebc9836e4d302d4 input=bec1271a33d47e67]*/ |
1155 | 0 | { |
1156 | 0 | double x, m; |
1157 | 0 | int e, shift, i, si, esign; |
1158 | | /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the |
1159 | | trailing NUL byte. */ |
1160 | 0 | char s[(TOHEX_NBITS-1)/4+3]; |
1161 | |
|
1162 | 0 | CONVERT_TO_DOUBLE(self, x); |
1163 | |
|
1164 | 0 | if (isnan(x) || isinf(x)) |
1165 | 0 | return float_repr(self); |
1166 | | |
1167 | 0 | if (x == 0.0) { |
1168 | 0 | if (copysign(1.0, x) == -1.0) |
1169 | 0 | return PyUnicode_FromString("-0x0.0p+0"); |
1170 | 0 | else |
1171 | 0 | return PyUnicode_FromString("0x0.0p+0"); |
1172 | 0 | } |
1173 | | |
1174 | 0 | m = frexp(fabs(x), &e); |
1175 | 0 | shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0); |
1176 | 0 | m = ldexp(m, shift); |
1177 | 0 | e -= shift; |
1178 | |
|
1179 | 0 | si = 0; |
1180 | 0 | s[si] = char_from_hex((int)m); |
1181 | 0 | si++; |
1182 | 0 | m -= (int)m; |
1183 | 0 | s[si] = '.'; |
1184 | 0 | si++; |
1185 | 0 | for (i=0; i < (TOHEX_NBITS-1)/4; i++) { |
1186 | 0 | m *= 16.0; |
1187 | 0 | s[si] = char_from_hex((int)m); |
1188 | 0 | si++; |
1189 | 0 | m -= (int)m; |
1190 | 0 | } |
1191 | 0 | s[si] = '\0'; |
1192 | |
|
1193 | 0 | if (e < 0) { |
1194 | 0 | esign = (int)'-'; |
1195 | 0 | e = -e; |
1196 | 0 | } |
1197 | 0 | else |
1198 | 0 | esign = (int)'+'; |
1199 | |
|
1200 | 0 | if (x < 0.0) |
1201 | 0 | return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e); |
1202 | 0 | else |
1203 | 0 | return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e); |
1204 | 0 | } |
1205 | | |
1206 | | /* Convert a hexadecimal string to a float. */ |
1207 | | |
1208 | | /*[clinic input] |
1209 | | @classmethod |
1210 | | float.fromhex |
1211 | | |
1212 | | string: object |
1213 | | / |
1214 | | |
1215 | | Create a floating-point number from a hexadecimal string. |
1216 | | |
1217 | | >>> float.fromhex('0x1.ffffp10') |
1218 | | 2047.984375 |
1219 | | >>> float.fromhex('-0x1p-1074') |
1220 | | -5e-324 |
1221 | | [clinic start generated code]*/ |
1222 | | |
1223 | | static PyObject * |
1224 | | float_fromhex_impl(PyTypeObject *type, PyObject *string) |
1225 | | /*[clinic end generated code: output=c54b4923552e5af5 input=0407bebd354bca89]*/ |
1226 | 0 | { |
1227 | 0 | PyObject *result; |
1228 | 0 | double x; |
1229 | 0 | long exp, top_exp, lsb, key_digit; |
1230 | 0 | const char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end; |
1231 | 0 | int half_eps, digit, round_up, negate=0; |
1232 | 0 | Py_ssize_t length, ndigits, fdigits, i; |
1233 | | |
1234 | | /* |
1235 | | * For the sake of simplicity and correctness, we impose an artificial |
1236 | | * limit on ndigits, the total number of hex digits in the coefficient |
1237 | | * The limit is chosen to ensure that, writing exp for the exponent, |
1238 | | * |
1239 | | * (1) if exp > LONG_MAX/2 then the value of the hex string is |
1240 | | * guaranteed to overflow (provided it's nonzero) |
1241 | | * |
1242 | | * (2) if exp < LONG_MIN/2 then the value of the hex string is |
1243 | | * guaranteed to underflow to 0. |
1244 | | * |
1245 | | * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of |
1246 | | * overflow in the calculation of exp and top_exp below. |
1247 | | * |
1248 | | * More specifically, ndigits is assumed to satisfy the following |
1249 | | * inequalities: |
1250 | | * |
1251 | | * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2 |
1252 | | * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP |
1253 | | * |
1254 | | * If either of these inequalities is not satisfied, a ValueError is |
1255 | | * raised. Otherwise, write x for the value of the hex string, and |
1256 | | * assume x is nonzero. Then |
1257 | | * |
1258 | | * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits). |
1259 | | * |
1260 | | * Now if exp > LONG_MAX/2 then: |
1261 | | * |
1262 | | * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP) |
1263 | | * = DBL_MAX_EXP |
1264 | | * |
1265 | | * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C |
1266 | | * double, so overflows. If exp < LONG_MIN/2, then |
1267 | | * |
1268 | | * exp + 4*ndigits <= LONG_MIN/2 - 1 + ( |
1269 | | * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2) |
1270 | | * = DBL_MIN_EXP - DBL_MANT_DIG - 1 |
1271 | | * |
1272 | | * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0 |
1273 | | * when converted to a C double. |
1274 | | * |
1275 | | * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both |
1276 | | * exp+4*ndigits and exp-4*ndigits are within the range of a long. |
1277 | | */ |
1278 | |
|
1279 | 0 | s = PyUnicode_AsUTF8AndSize(string, &length); |
1280 | 0 | if (s == NULL) |
1281 | 0 | return NULL; |
1282 | 0 | s_end = s + length; |
1283 | | |
1284 | | /******************** |
1285 | | * Parse the string * |
1286 | | ********************/ |
1287 | | |
1288 | | /* leading whitespace */ |
1289 | 0 | while (Py_ISSPACE(*s)) |
1290 | 0 | s++; |
1291 | | |
1292 | | /* infinities and nans */ |
1293 | 0 | x = _Py_parse_inf_or_nan(s, (char **)&coeff_end); |
1294 | 0 | if (coeff_end != s) { |
1295 | 0 | s = coeff_end; |
1296 | 0 | goto finished; |
1297 | 0 | } |
1298 | | |
1299 | | /* optional sign */ |
1300 | 0 | if (*s == '-') { |
1301 | 0 | s++; |
1302 | 0 | negate = 1; |
1303 | 0 | } |
1304 | 0 | else if (*s == '+') |
1305 | 0 | s++; |
1306 | | |
1307 | | /* [0x] */ |
1308 | 0 | s_store = s; |
1309 | 0 | if (*s == '0') { |
1310 | 0 | s++; |
1311 | 0 | if (*s == 'x' || *s == 'X') |
1312 | 0 | s++; |
1313 | 0 | else |
1314 | 0 | s = s_store; |
1315 | 0 | } |
1316 | | |
1317 | | /* coefficient: <integer> [. <fraction>] */ |
1318 | 0 | coeff_start = s; |
1319 | 0 | while (hex_from_char(*s) >= 0) |
1320 | 0 | s++; |
1321 | 0 | s_store = s; |
1322 | 0 | if (*s == '.') { |
1323 | 0 | s++; |
1324 | 0 | while (hex_from_char(*s) >= 0) |
1325 | 0 | s++; |
1326 | 0 | coeff_end = s-1; |
1327 | 0 | } |
1328 | 0 | else |
1329 | 0 | coeff_end = s; |
1330 | | |
1331 | | /* ndigits = total # of hex digits; fdigits = # after point */ |
1332 | 0 | ndigits = coeff_end - coeff_start; |
1333 | 0 | fdigits = coeff_end - s_store; |
1334 | 0 | if (ndigits == 0) |
1335 | 0 | goto parse_error; |
1336 | 0 | if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2, |
1337 | 0 | LONG_MAX/2 + 1 - DBL_MAX_EXP)/4) |
1338 | 0 | goto insane_length_error; |
1339 | | |
1340 | | /* [p <exponent>] */ |
1341 | 0 | if (*s == 'p' || *s == 'P') { |
1342 | 0 | s++; |
1343 | 0 | exp_start = s; |
1344 | 0 | if (*s == '-' || *s == '+') |
1345 | 0 | s++; |
1346 | 0 | if (!('0' <= *s && *s <= '9')) |
1347 | 0 | goto parse_error; |
1348 | 0 | s++; |
1349 | 0 | while ('0' <= *s && *s <= '9') |
1350 | 0 | s++; |
1351 | 0 | exp = strtol(exp_start, NULL, 10); |
1352 | 0 | } |
1353 | 0 | else |
1354 | 0 | exp = 0; |
1355 | | |
1356 | | /* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */ |
1357 | 0 | #define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \ |
1358 | 0 | coeff_end-(j) : \ |
1359 | 0 | coeff_end-1-(j))) |
1360 | | |
1361 | | /******************************************* |
1362 | | * Compute rounded value of the hex string * |
1363 | | *******************************************/ |
1364 | | |
1365 | | /* Discard leading zeros, and catch extreme overflow and underflow */ |
1366 | 0 | while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0) |
1367 | 0 | ndigits--; |
1368 | 0 | if (ndigits == 0 || exp < LONG_MIN/2) { |
1369 | 0 | x = 0.0; |
1370 | 0 | goto finished; |
1371 | 0 | } |
1372 | 0 | if (exp > LONG_MAX/2) |
1373 | 0 | goto overflow_error; |
1374 | | |
1375 | | /* Adjust exponent for fractional part. */ |
1376 | 0 | exp = exp - 4*((long)fdigits); |
1377 | | |
1378 | | /* top_exp = 1 more than exponent of most sig. bit of coefficient */ |
1379 | 0 | top_exp = exp + 4*((long)ndigits - 1); |
1380 | 0 | for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2) |
1381 | 0 | top_exp++; |
1382 | | |
1383 | | /* catch almost all nonextreme cases of overflow and underflow here */ |
1384 | 0 | if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) { |
1385 | 0 | x = 0.0; |
1386 | 0 | goto finished; |
1387 | 0 | } |
1388 | 0 | if (top_exp > DBL_MAX_EXP) |
1389 | 0 | goto overflow_error; |
1390 | | |
1391 | | /* lsb = exponent of least significant bit of the *rounded* value. |
1392 | | This is top_exp - DBL_MANT_DIG unless result is subnormal. */ |
1393 | 0 | lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG; |
1394 | |
|
1395 | 0 | x = 0.0; |
1396 | 0 | if (exp >= lsb) { |
1397 | | /* no rounding required */ |
1398 | 0 | for (i = ndigits-1; i >= 0; i--) |
1399 | 0 | x = 16.0*x + HEX_DIGIT(i); |
1400 | 0 | x = ldexp(x, (int)(exp)); |
1401 | 0 | goto finished; |
1402 | 0 | } |
1403 | | /* rounding required. key_digit is the index of the hex digit |
1404 | | containing the first bit to be rounded away. */ |
1405 | 0 | half_eps = 1 << (int)((lsb - exp - 1) % 4); |
1406 | 0 | key_digit = (lsb - exp - 1) / 4; |
1407 | 0 | for (i = ndigits-1; i > key_digit; i--) |
1408 | 0 | x = 16.0*x + HEX_DIGIT(i); |
1409 | 0 | digit = HEX_DIGIT(key_digit); |
1410 | 0 | x = 16.0*x + (double)(digit & (16-2*half_eps)); |
1411 | | |
1412 | | /* round-half-even: round up if bit lsb-1 is 1 and at least one of |
1413 | | bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */ |
1414 | 0 | if ((digit & half_eps) != 0) { |
1415 | 0 | round_up = 0; |
1416 | 0 | if ((digit & (3*half_eps-1)) != 0 || (half_eps == 8 && |
1417 | 0 | key_digit+1 < ndigits && (HEX_DIGIT(key_digit+1) & 1) != 0)) |
1418 | 0 | round_up = 1; |
1419 | 0 | else |
1420 | 0 | for (i = key_digit-1; i >= 0; i--) |
1421 | 0 | if (HEX_DIGIT(i) != 0) { |
1422 | 0 | round_up = 1; |
1423 | 0 | break; |
1424 | 0 | } |
1425 | 0 | if (round_up) { |
1426 | 0 | x += 2*half_eps; |
1427 | 0 | if (top_exp == DBL_MAX_EXP && |
1428 | 0 | x == ldexp((double)(2*half_eps), DBL_MANT_DIG)) |
1429 | | /* overflow corner case: pre-rounded value < |
1430 | | 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */ |
1431 | 0 | goto overflow_error; |
1432 | 0 | } |
1433 | 0 | } |
1434 | 0 | x = ldexp(x, (int)(exp+4*key_digit)); |
1435 | |
|
1436 | 0 | finished: |
1437 | | /* optional trailing whitespace leading to the end of the string */ |
1438 | 0 | while (Py_ISSPACE(*s)) |
1439 | 0 | s++; |
1440 | 0 | if (s != s_end) |
1441 | 0 | goto parse_error; |
1442 | 0 | result = PyFloat_FromDouble(negate ? -x : x); |
1443 | 0 | if (type != &PyFloat_Type && result != NULL) { |
1444 | 0 | Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result)); |
1445 | 0 | } |
1446 | 0 | return result; |
1447 | | |
1448 | 0 | overflow_error: |
1449 | 0 | PyErr_SetString(PyExc_OverflowError, |
1450 | 0 | "hexadecimal value too large to represent as a float"); |
1451 | 0 | return NULL; |
1452 | | |
1453 | 0 | parse_error: |
1454 | 0 | PyErr_SetString(PyExc_ValueError, |
1455 | 0 | "invalid hexadecimal floating-point string"); |
1456 | 0 | return NULL; |
1457 | | |
1458 | 0 | insane_length_error: |
1459 | 0 | PyErr_SetString(PyExc_ValueError, |
1460 | 0 | "hexadecimal string too long to convert"); |
1461 | 0 | return NULL; |
1462 | 0 | } |
1463 | | |
1464 | | /*[clinic input] |
1465 | | @permit_long_summary |
1466 | | float.as_integer_ratio |
1467 | | |
1468 | | Return a pair of integers, whose ratio is exactly equal to the original float. |
1469 | | |
1470 | | The ratio is in lowest terms and has a positive denominator. Raise |
1471 | | OverflowError on infinities and a ValueError on NaNs. |
1472 | | |
1473 | | >>> (10.0).as_integer_ratio() |
1474 | | (10, 1) |
1475 | | >>> (0.0).as_integer_ratio() |
1476 | | (0, 1) |
1477 | | >>> (-.25).as_integer_ratio() |
1478 | | (-1, 4) |
1479 | | [clinic start generated code]*/ |
1480 | | |
1481 | | static PyObject * |
1482 | | float_as_integer_ratio_impl(PyObject *self) |
1483 | | /*[clinic end generated code: output=65f25f0d8d30a712 input=75ae9be7cecd82a3]*/ |
1484 | 0 | { |
1485 | 0 | double self_double; |
1486 | 0 | double float_part; |
1487 | 0 | int exponent; |
1488 | 0 | int i; |
1489 | |
|
1490 | 0 | PyObject *py_exponent = NULL; |
1491 | 0 | PyObject *numerator = NULL; |
1492 | 0 | PyObject *denominator = NULL; |
1493 | 0 | PyObject *result_pair = NULL; |
1494 | 0 | PyNumberMethods *long_methods = PyLong_Type.tp_as_number; |
1495 | |
|
1496 | 0 | CONVERT_TO_DOUBLE(self, self_double); |
1497 | |
|
1498 | 0 | if (isinf(self_double)) { |
1499 | 0 | PyErr_SetString(PyExc_OverflowError, |
1500 | 0 | "cannot convert Infinity to integer ratio"); |
1501 | 0 | return NULL; |
1502 | 0 | } |
1503 | 0 | if (isnan(self_double)) { |
1504 | 0 | PyErr_SetString(PyExc_ValueError, |
1505 | 0 | "cannot convert NaN to integer ratio"); |
1506 | 0 | return NULL; |
1507 | 0 | } |
1508 | | |
1509 | 0 | float_part = frexp(self_double, &exponent); /* self_double == float_part * 2**exponent exactly */ |
1510 | |
|
1511 | 0 | for (i=0; i<300 && float_part != floor(float_part) ; i++) { |
1512 | 0 | float_part *= 2.0; |
1513 | 0 | exponent--; |
1514 | 0 | } |
1515 | | /* self == float_part * 2**exponent exactly and float_part is integral. |
1516 | | If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part |
1517 | | to be truncated by PyLong_FromDouble(). */ |
1518 | |
|
1519 | 0 | numerator = PyLong_FromDouble(float_part); |
1520 | 0 | if (numerator == NULL) |
1521 | 0 | goto error; |
1522 | 0 | denominator = PyLong_FromLong(1); |
1523 | 0 | if (denominator == NULL) |
1524 | 0 | goto error; |
1525 | 0 | py_exponent = PyLong_FromLong(Py_ABS(exponent)); |
1526 | 0 | if (py_exponent == NULL) |
1527 | 0 | goto error; |
1528 | | |
1529 | | /* fold in 2**exponent */ |
1530 | 0 | if (exponent > 0) { |
1531 | 0 | Py_SETREF(numerator, |
1532 | 0 | long_methods->nb_lshift(numerator, py_exponent)); |
1533 | 0 | if (numerator == NULL) |
1534 | 0 | goto error; |
1535 | 0 | } |
1536 | 0 | else { |
1537 | 0 | Py_SETREF(denominator, |
1538 | 0 | long_methods->nb_lshift(denominator, py_exponent)); |
1539 | 0 | if (denominator == NULL) |
1540 | 0 | goto error; |
1541 | 0 | } |
1542 | | |
1543 | 0 | result_pair = PyTuple_Pack(2, numerator, denominator); |
1544 | |
|
1545 | 0 | error: |
1546 | 0 | Py_XDECREF(py_exponent); |
1547 | 0 | Py_XDECREF(denominator); |
1548 | 0 | Py_XDECREF(numerator); |
1549 | 0 | return result_pair; |
1550 | 0 | } |
1551 | | |
1552 | | static PyObject * |
1553 | | float_subtype_new(PyTypeObject *type, PyObject *x); |
1554 | | |
1555 | | /*[clinic input] |
1556 | | @classmethod |
1557 | | float.__new__ as float_new |
1558 | | x: object(c_default="NULL") = 0 |
1559 | | / |
1560 | | |
1561 | | Convert a string or number to a floating-point number, if possible. |
1562 | | [clinic start generated code]*/ |
1563 | | |
1564 | | static PyObject * |
1565 | | float_new_impl(PyTypeObject *type, PyObject *x) |
1566 | | /*[clinic end generated code: output=ccf1e8dc460ba6ba input=55909f888aa0c8a6]*/ |
1567 | 497k | { |
1568 | 497k | if (type != &PyFloat_Type) { |
1569 | 0 | if (x == NULL) { |
1570 | 0 | x = _PyLong_GetZero(); |
1571 | 0 | } |
1572 | 0 | return float_subtype_new(type, x); /* Wimp out */ |
1573 | 0 | } |
1574 | | |
1575 | 497k | if (x == NULL) { |
1576 | 0 | return PyFloat_FromDouble(0.0); |
1577 | 0 | } |
1578 | | /* If it's a string, but not a string subclass, use |
1579 | | PyFloat_FromString. */ |
1580 | 497k | if (PyUnicode_CheckExact(x)) |
1581 | 497k | return PyFloat_FromString(x); |
1582 | 8 | return PyNumber_Float(x); |
1583 | 497k | } |
1584 | | |
1585 | | /* Wimpy, slow approach to tp_new calls for subtypes of float: |
1586 | | first create a regular float from whatever arguments we got, |
1587 | | then allocate a subtype instance and initialize its ob_fval |
1588 | | from the regular float. The regular float is then thrown away. |
1589 | | */ |
1590 | | static PyObject * |
1591 | | float_subtype_new(PyTypeObject *type, PyObject *x) |
1592 | 0 | { |
1593 | 0 | PyObject *tmp, *newobj; |
1594 | |
|
1595 | 0 | assert(PyType_IsSubtype(type, &PyFloat_Type)); |
1596 | 0 | tmp = float_new_impl(&PyFloat_Type, x); |
1597 | 0 | if (tmp == NULL) |
1598 | 0 | return NULL; |
1599 | 0 | assert(PyFloat_Check(tmp)); |
1600 | 0 | newobj = type->tp_alloc(type, 0); |
1601 | 0 | if (newobj == NULL) { |
1602 | 0 | Py_DECREF(tmp); |
1603 | 0 | return NULL; |
1604 | 0 | } |
1605 | 0 | ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval; |
1606 | 0 | Py_DECREF(tmp); |
1607 | 0 | return newobj; |
1608 | 0 | } |
1609 | | |
1610 | | static PyObject * |
1611 | | float_vectorcall(PyObject *type, PyObject *const *args, |
1612 | | size_t nargsf, PyObject *kwnames) |
1613 | 497k | { |
1614 | 497k | if (!_PyArg_NoKwnames("float", kwnames)) { |
1615 | 0 | return NULL; |
1616 | 0 | } |
1617 | | |
1618 | 497k | Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); |
1619 | 497k | if (!_PyArg_CheckPositional("float", nargs, 0, 1)) { |
1620 | 0 | return NULL; |
1621 | 0 | } |
1622 | | |
1623 | 497k | PyObject *x = nargs >= 1 ? args[0] : NULL; |
1624 | 497k | return float_new_impl(_PyType_CAST(type), x); |
1625 | 497k | } |
1626 | | |
1627 | | |
1628 | | /*[clinic input] |
1629 | | @classmethod |
1630 | | float.from_number |
1631 | | |
1632 | | number: object |
1633 | | / |
1634 | | |
1635 | | Convert real number to a floating-point number. |
1636 | | [clinic start generated code]*/ |
1637 | | |
1638 | | static PyObject * |
1639 | | float_from_number_impl(PyTypeObject *type, PyObject *number) |
1640 | | /*[clinic end generated code: output=dda7e4466ab7068d input=1f8424d9bc11866a]*/ |
1641 | 0 | { |
1642 | 0 | if (PyFloat_CheckExact(number) && type == &PyFloat_Type) { |
1643 | 0 | Py_INCREF(number); |
1644 | 0 | return number; |
1645 | 0 | } |
1646 | 0 | double x = PyFloat_AsDouble(number); |
1647 | 0 | if (x == -1.0 && PyErr_Occurred()) { |
1648 | 0 | return NULL; |
1649 | 0 | } |
1650 | 0 | PyObject *result = PyFloat_FromDouble(x); |
1651 | 0 | if (type != &PyFloat_Type && result != NULL) { |
1652 | 0 | Py_SETREF(result, PyObject_CallOneArg((PyObject *)type, result)); |
1653 | 0 | } |
1654 | 0 | return result; |
1655 | 0 | } |
1656 | | |
1657 | | |
1658 | | /*[clinic input] |
1659 | | float.__getnewargs__ |
1660 | | [clinic start generated code]*/ |
1661 | | |
1662 | | static PyObject * |
1663 | | float___getnewargs___impl(PyObject *self) |
1664 | | /*[clinic end generated code: output=873258c9d206b088 input=002279d1d77891e6]*/ |
1665 | 0 | { |
1666 | 0 | return Py_BuildValue("(d)", ((PyFloatObject *)self)->ob_fval); |
1667 | 0 | } |
1668 | | |
1669 | | |
1670 | | /*[clinic input] |
1671 | | @permit_long_docstring_body |
1672 | | @classmethod |
1673 | | float.__getformat__ |
1674 | | |
1675 | | typestr: str |
1676 | | Must be 'double' or 'float'. |
1677 | | / |
1678 | | |
1679 | | You probably don't want to use this function. |
1680 | | |
1681 | | It exists mainly to be used in Python's test suite. |
1682 | | |
1683 | | This function returns whichever of 'IEEE, big-endian' or 'IEEE, |
1684 | | little-endian' best describes the format of floating-point numbers used by the |
1685 | | C type named by typestr. |
1686 | | [clinic start generated code]*/ |
1687 | | |
1688 | | static PyObject * |
1689 | | float___getformat___impl(PyTypeObject *type, const char *typestr) |
1690 | | /*[clinic end generated code: output=2bfb987228cc9628 input=0ae1ba35d192f704]*/ |
1691 | 0 | { |
1692 | 0 | if (strcmp(typestr, "double") != 0 && strcmp(typestr, "float") != 0) { |
1693 | 0 | PyErr_SetString(PyExc_ValueError, |
1694 | 0 | "__getformat__() argument 1 must be " |
1695 | 0 | "'double' or 'float'"); |
1696 | 0 | return NULL; |
1697 | 0 | } |
1698 | 0 | return PyUnicode_FromString(_PY_FLOAT_LITTLE_ENDIAN ? |
1699 | 0 | "IEEE, little-endian" : "IEEE, big-endian"); |
1700 | 0 | } |
1701 | | |
1702 | | static PyObject * |
1703 | | float_getreal(PyObject *v, void *Py_UNUSED(closure)) |
1704 | 0 | { |
1705 | 0 | return float_float(v); |
1706 | 0 | } |
1707 | | |
1708 | | static PyObject * |
1709 | | float_getimag(PyObject *Py_UNUSED(v), void *Py_UNUSED(closure)) |
1710 | 0 | { |
1711 | 0 | return PyFloat_FromDouble(0.0); |
1712 | 0 | } |
1713 | | |
1714 | | /*[clinic input] |
1715 | | float.__format__ |
1716 | | |
1717 | | format_spec: unicode |
1718 | | / |
1719 | | |
1720 | | Formats the float according to format_spec. |
1721 | | [clinic start generated code]*/ |
1722 | | |
1723 | | static PyObject * |
1724 | | float___format___impl(PyObject *self, PyObject *format_spec) |
1725 | | /*[clinic end generated code: output=b260e52a47eade56 input=2ece1052211fd0e6]*/ |
1726 | 0 | { |
1727 | 0 | _PyUnicodeWriter writer; |
1728 | 0 | int ret; |
1729 | |
|
1730 | 0 | _PyUnicodeWriter_Init(&writer); |
1731 | 0 | ret = _PyFloat_FormatAdvancedWriter( |
1732 | 0 | &writer, |
1733 | 0 | self, |
1734 | 0 | format_spec, 0, PyUnicode_GET_LENGTH(format_spec)); |
1735 | 0 | if (ret == -1) { |
1736 | 0 | _PyUnicodeWriter_Dealloc(&writer); |
1737 | 0 | return NULL; |
1738 | 0 | } |
1739 | 0 | return _PyUnicodeWriter_Finish(&writer); |
1740 | 0 | } |
1741 | | |
1742 | | static PyMethodDef float_methods[] = { |
1743 | | FLOAT_FROM_NUMBER_METHODDEF |
1744 | | FLOAT_CONJUGATE_METHODDEF |
1745 | | FLOAT___TRUNC___METHODDEF |
1746 | | FLOAT___FLOOR___METHODDEF |
1747 | | FLOAT___CEIL___METHODDEF |
1748 | | FLOAT___ROUND___METHODDEF |
1749 | | FLOAT_AS_INTEGER_RATIO_METHODDEF |
1750 | | FLOAT_FROMHEX_METHODDEF |
1751 | | FLOAT_HEX_METHODDEF |
1752 | | FLOAT_IS_INTEGER_METHODDEF |
1753 | | FLOAT___GETNEWARGS___METHODDEF |
1754 | | FLOAT___GETFORMAT___METHODDEF |
1755 | | FLOAT___FORMAT___METHODDEF |
1756 | | {NULL, NULL} /* sentinel */ |
1757 | | }; |
1758 | | |
1759 | | static PyGetSetDef float_getset[] = { |
1760 | | {"real", |
1761 | | float_getreal, NULL, |
1762 | | "the real part of a complex number", |
1763 | | NULL}, |
1764 | | {"imag", |
1765 | | float_getimag, NULL, |
1766 | | "the imaginary part of a complex number", |
1767 | | NULL}, |
1768 | | {NULL} /* Sentinel */ |
1769 | | }; |
1770 | | |
1771 | | |
1772 | | static PyNumberMethods float_as_number = { |
1773 | | float_add, /* nb_add */ |
1774 | | float_sub, /* nb_subtract */ |
1775 | | float_mul, /* nb_multiply */ |
1776 | | float_rem, /* nb_remainder */ |
1777 | | float_divmod, /* nb_divmod */ |
1778 | | float_pow, /* nb_power */ |
1779 | | float_neg, /* nb_negative */ |
1780 | | float_float, /* nb_positive */ |
1781 | | float_abs, /* nb_absolute */ |
1782 | | float_bool, /* nb_bool */ |
1783 | | 0, /* nb_invert */ |
1784 | | 0, /* nb_lshift */ |
1785 | | 0, /* nb_rshift */ |
1786 | | 0, /* nb_and */ |
1787 | | 0, /* nb_xor */ |
1788 | | 0, /* nb_or */ |
1789 | | float___trunc___impl, /* nb_int */ |
1790 | | 0, /* nb_reserved */ |
1791 | | float_float, /* nb_float */ |
1792 | | 0, /* nb_inplace_add */ |
1793 | | 0, /* nb_inplace_subtract */ |
1794 | | 0, /* nb_inplace_multiply */ |
1795 | | 0, /* nb_inplace_remainder */ |
1796 | | 0, /* nb_inplace_power */ |
1797 | | 0, /* nb_inplace_lshift */ |
1798 | | 0, /* nb_inplace_rshift */ |
1799 | | 0, /* nb_inplace_and */ |
1800 | | 0, /* nb_inplace_xor */ |
1801 | | 0, /* nb_inplace_or */ |
1802 | | float_floor_div, /* nb_floor_divide */ |
1803 | | float_div, /* nb_true_divide */ |
1804 | | 0, /* nb_inplace_floor_divide */ |
1805 | | 0, /* nb_inplace_true_divide */ |
1806 | | }; |
1807 | | |
1808 | | PyTypeObject PyFloat_Type = { |
1809 | | PyVarObject_HEAD_INIT(&PyType_Type, 0) |
1810 | | "float", |
1811 | | sizeof(PyFloatObject), |
1812 | | 0, |
1813 | | float_dealloc, /* tp_dealloc */ |
1814 | | 0, /* tp_vectorcall_offset */ |
1815 | | 0, /* tp_getattr */ |
1816 | | 0, /* tp_setattr */ |
1817 | | 0, /* tp_as_async */ |
1818 | | float_repr, /* tp_repr */ |
1819 | | &float_as_number, /* tp_as_number */ |
1820 | | 0, /* tp_as_sequence */ |
1821 | | 0, /* tp_as_mapping */ |
1822 | | float_hash, /* tp_hash */ |
1823 | | 0, /* tp_call */ |
1824 | | 0, /* tp_str */ |
1825 | | PyObject_GenericGetAttr, /* tp_getattro */ |
1826 | | 0, /* tp_setattro */ |
1827 | | 0, /* tp_as_buffer */ |
1828 | | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | |
1829 | | _Py_TPFLAGS_MATCH_SELF, /* tp_flags */ |
1830 | | float_new__doc__, /* tp_doc */ |
1831 | | 0, /* tp_traverse */ |
1832 | | 0, /* tp_clear */ |
1833 | | float_richcompare, /* tp_richcompare */ |
1834 | | 0, /* tp_weaklistoffset */ |
1835 | | 0, /* tp_iter */ |
1836 | | 0, /* tp_iternext */ |
1837 | | float_methods, /* tp_methods */ |
1838 | | 0, /* tp_members */ |
1839 | | float_getset, /* tp_getset */ |
1840 | | 0, /* tp_base */ |
1841 | | 0, /* tp_dict */ |
1842 | | 0, /* tp_descr_get */ |
1843 | | 0, /* tp_descr_set */ |
1844 | | 0, /* tp_dictoffset */ |
1845 | | 0, /* tp_init */ |
1846 | | 0, /* tp_alloc */ |
1847 | | float_new, /* tp_new */ |
1848 | | .tp_vectorcall = float_vectorcall, |
1849 | | .tp_version_tag = _Py_TYPE_VERSION_FLOAT, |
1850 | | }; |
1851 | | |
1852 | | PyStatus |
1853 | | _PyFloat_InitTypes(PyInterpreterState *interp) |
1854 | 36 | { |
1855 | | /* Init float info */ |
1856 | 36 | if (_PyStructSequence_InitBuiltin(interp, &FloatInfoType, |
1857 | 36 | &floatinfo_desc) < 0) |
1858 | 0 | { |
1859 | 0 | return _PyStatus_ERR("can't init float info type"); |
1860 | 0 | } |
1861 | | |
1862 | 36 | return _PyStatus_OK(); |
1863 | 36 | } |
1864 | | |
1865 | | void |
1866 | | _PyFloat_FiniType(PyInterpreterState *interp) |
1867 | 0 | { |
1868 | 0 | _PyStructSequence_FiniBuiltin(interp, &FloatInfoType); |
1869 | 0 | } |
1870 | | |
1871 | | /* Print summary info about the state of the optimized allocator */ |
1872 | | void |
1873 | | _PyFloat_DebugMallocStats(FILE *out) |
1874 | 0 | { |
1875 | 0 | _PyDebugAllocatorStats(out, |
1876 | 0 | "free PyFloatObject", |
1877 | 0 | _Py_FREELIST_SIZE(floats), |
1878 | 0 | sizeof(PyFloatObject)); |
1879 | 0 | } |
1880 | | |
1881 | | |
1882 | | /*---------------------------------------------------------------------------- |
1883 | | * PyFloat_{Pack,Unpack}{2,4,8}. See floatobject.h. |
1884 | | * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in: |
1885 | | * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c |
1886 | | * We use: |
1887 | | * bits = (unsigned short)f; Note the truncation |
1888 | | * if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) { |
1889 | | * bits++; |
1890 | | * } |
1891 | | */ |
1892 | | |
1893 | | int |
1894 | | PyFloat_Pack2(double x, char *data, int le) |
1895 | 0 | { |
1896 | 0 | unsigned char *p = (unsigned char *)data; |
1897 | 0 | unsigned char sign; |
1898 | 0 | int e; |
1899 | 0 | double f; |
1900 | 0 | unsigned short bits; |
1901 | 0 | int incr = 1; |
1902 | |
|
1903 | 0 | if (x == 0.0) { |
1904 | 0 | sign = (copysign(1.0, x) == -1.0); |
1905 | 0 | e = 0; |
1906 | 0 | bits = 0; |
1907 | 0 | } |
1908 | 0 | else if (isinf(x)) { |
1909 | 0 | sign = (x < 0.0); |
1910 | 0 | e = 0x1f; |
1911 | 0 | bits = 0; |
1912 | 0 | } |
1913 | 0 | else if (isnan(x)) { |
1914 | 0 | sign = (copysign(1.0, x) == -1.0); |
1915 | 0 | e = 0x1f; |
1916 | |
|
1917 | 0 | uint64_t v; |
1918 | 0 | memcpy(&v, &x, sizeof(v)); |
1919 | 0 | v &= 0xffc0000000000ULL; |
1920 | 0 | bits = (unsigned short)(v >> 42); /* NaN's type & payload */ |
1921 | | /* set qNaN if no payload */ |
1922 | 0 | if (!bits) { |
1923 | 0 | bits |= (1<<9); |
1924 | 0 | } |
1925 | 0 | } |
1926 | 0 | else { |
1927 | 0 | sign = (x < 0.0); |
1928 | 0 | if (sign) { |
1929 | 0 | x = -x; |
1930 | 0 | } |
1931 | |
|
1932 | 0 | f = frexp(x, &e); |
1933 | 0 | if (f < 0.5 || f >= 1.0) { |
1934 | 0 | PyErr_SetString(PyExc_SystemError, |
1935 | 0 | "frexp() result out of range"); |
1936 | 0 | return -1; |
1937 | 0 | } |
1938 | | |
1939 | | /* Normalize f to be in the range [1.0, 2.0) */ |
1940 | 0 | f *= 2.0; |
1941 | 0 | e--; |
1942 | |
|
1943 | 0 | if (e >= 16) { |
1944 | 0 | goto Overflow; |
1945 | 0 | } |
1946 | 0 | else if (e < -25) { |
1947 | | /* |x| < 2**-25. Underflow to zero. */ |
1948 | 0 | f = 0.0; |
1949 | 0 | e = 0; |
1950 | 0 | } |
1951 | 0 | else if (e < -14) { |
1952 | | /* |x| < 2**-14. Gradual underflow */ |
1953 | 0 | f = ldexp(f, 14 + e); |
1954 | 0 | e = 0; |
1955 | 0 | } |
1956 | 0 | else /* if (!(e == 0 && f == 0.0)) */ { |
1957 | 0 | e += 15; |
1958 | 0 | f -= 1.0; /* Get rid of leading 1 */ |
1959 | 0 | } |
1960 | | |
1961 | 0 | f *= 1024.0; /* 2**10 */ |
1962 | | /* Round to even */ |
1963 | 0 | bits = (unsigned short)f; /* Note the truncation */ |
1964 | 0 | assert(bits < 1024); |
1965 | 0 | assert(e < 31); |
1966 | 0 | if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) { |
1967 | 0 | ++bits; |
1968 | 0 | if (bits == 1024) { |
1969 | | /* The carry propagated out of a string of 10 1 bits. */ |
1970 | 0 | bits = 0; |
1971 | 0 | ++e; |
1972 | 0 | if (e == 31) |
1973 | 0 | goto Overflow; |
1974 | 0 | } |
1975 | 0 | } |
1976 | 0 | } |
1977 | | |
1978 | 0 | bits |= (e << 10) | (sign << 15); |
1979 | | |
1980 | | /* Write out result. */ |
1981 | 0 | if (le) { |
1982 | 0 | p += 1; |
1983 | 0 | incr = -1; |
1984 | 0 | } |
1985 | | |
1986 | | /* First byte */ |
1987 | 0 | *p = (unsigned char)((bits >> 8) & 0xFF); |
1988 | 0 | p += incr; |
1989 | | |
1990 | | /* Second byte */ |
1991 | 0 | *p = (unsigned char)(bits & 0xFF); |
1992 | |
|
1993 | 0 | return 0; |
1994 | | |
1995 | 0 | Overflow: |
1996 | 0 | PyErr_SetString(PyExc_OverflowError, |
1997 | 0 | "float too large to pack with e format"); |
1998 | 0 | return -1; |
1999 | 0 | } |
2000 | | |
2001 | | int |
2002 | | PyFloat_Pack4(double x, char *data, int le) |
2003 | 0 | { |
2004 | 0 | unsigned char *p = (unsigned char *)data; |
2005 | 0 | float y = (float)x; |
2006 | 0 | int i, incr = 1; |
2007 | |
|
2008 | 0 | if (isinf(y) && !isinf(x)) { |
2009 | 0 | PyErr_SetString(PyExc_OverflowError, |
2010 | 0 | "float too large to pack with f format"); |
2011 | 0 | return -1; |
2012 | 0 | } |
2013 | | |
2014 | | /* correct y if x was a sNaN, transformed to qNaN by conversion */ |
2015 | 0 | if (isnan(x)) { |
2016 | 0 | uint64_t v; |
2017 | |
|
2018 | 0 | memcpy(&v, &x, 8); |
2019 | 0 | #ifndef __riscv |
2020 | 0 | if ((v & (1ULL << 51)) == 0) { |
2021 | 0 | uint32_t u32; |
2022 | 0 | memcpy(&u32, &y, 4); |
2023 | | /* if have payload, make sNaN */ |
2024 | 0 | if (u32 & 0x3fffff) { |
2025 | 0 | u32 &= ~(1 << 22); |
2026 | 0 | } |
2027 | 0 | memcpy(&y, &u32, 4); |
2028 | 0 | } |
2029 | | #else |
2030 | | uint32_t u32; |
2031 | | |
2032 | | memcpy(&u32, &y, 4); |
2033 | | /* Workaround RISC-V: "If a NaN value is converted to a |
2034 | | * different floating-point type, the result is the |
2035 | | * canonical NaN of the new type". The canonical NaN here |
2036 | | * is a positive qNaN with zero payload. */ |
2037 | | if (v & (1ULL << 63)) { |
2038 | | u32 |= (1 << 31); /* set sign */ |
2039 | | } |
2040 | | /* add payload */ |
2041 | | u32 -= (u32 & 0x3fffff); |
2042 | | u32 += (uint32_t)((v & 0x7ffffffffffffULL) >> 29); |
2043 | | /* if have payload, make sNaN */ |
2044 | | if ((v & (1ULL << 51)) == 0 && (u32 & 0x3fffff)) { |
2045 | | u32 &= ~(1 << 22); |
2046 | | } |
2047 | | |
2048 | | memcpy(&y, &u32, 4); |
2049 | | #endif |
2050 | 0 | } |
2051 | |
|
2052 | 0 | unsigned char s[sizeof(float)]; |
2053 | 0 | memcpy(s, &y, sizeof(float)); |
2054 | |
|
2055 | 0 | if ((_PY_FLOAT_LITTLE_ENDIAN && !le) || (_PY_FLOAT_BIG_ENDIAN && le)) { |
2056 | 0 | p += 3; |
2057 | 0 | incr = -1; |
2058 | 0 | } |
2059 | |
|
2060 | 0 | for (i = 0; i < 4; i++) { |
2061 | 0 | *p = s[i]; |
2062 | 0 | p += incr; |
2063 | 0 | } |
2064 | 0 | return 0; |
2065 | 0 | } |
2066 | | |
2067 | | int |
2068 | | PyFloat_Pack8(double x, char *data, int le) |
2069 | 477 | { |
2070 | 477 | unsigned char *p = (unsigned char *)data; |
2071 | 477 | unsigned char as_bytes[8]; |
2072 | 477 | memcpy(as_bytes, &x, 8); |
2073 | 477 | const unsigned char *s = as_bytes; |
2074 | 477 | int i, incr = 1; |
2075 | | |
2076 | 477 | if ((_PY_FLOAT_LITTLE_ENDIAN && !le) || (_PY_FLOAT_BIG_ENDIAN && le)) { |
2077 | 462 | p += 7; |
2078 | 462 | incr = -1; |
2079 | 462 | } |
2080 | | |
2081 | 4.29k | for (i = 0; i < 8; i++) { |
2082 | 3.81k | *p = *s++; |
2083 | 3.81k | p += incr; |
2084 | 3.81k | } |
2085 | 477 | return 0; |
2086 | 477 | } |
2087 | | |
2088 | | double |
2089 | | PyFloat_Unpack2(const char *data, int le) |
2090 | 0 | { |
2091 | 0 | unsigned char *p = (unsigned char *)data; |
2092 | 0 | unsigned char sign; |
2093 | 0 | int e; |
2094 | 0 | unsigned int f; |
2095 | 0 | double x; |
2096 | 0 | int incr = 1; |
2097 | |
|
2098 | 0 | if (le) { |
2099 | 0 | p += 1; |
2100 | 0 | incr = -1; |
2101 | 0 | } |
2102 | | |
2103 | | /* First byte */ |
2104 | 0 | sign = (*p >> 7) & 1; |
2105 | 0 | e = (*p & 0x7C) >> 2; |
2106 | 0 | f = (*p & 0x03) << 8; |
2107 | 0 | p += incr; |
2108 | | |
2109 | | /* Second byte */ |
2110 | 0 | f |= *p; |
2111 | |
|
2112 | 0 | if (e == 0x1f) { |
2113 | 0 | if (f == 0) { |
2114 | | /* Infinity */ |
2115 | 0 | return sign ? -INFINITY : INFINITY; |
2116 | 0 | } |
2117 | 0 | else { |
2118 | | /* NaN */ |
2119 | 0 | uint64_t v = sign ? 0xfff0000000000000ULL : 0x7ff0000000000000ULL; |
2120 | |
|
2121 | 0 | v += (uint64_t)f << 42; /* add NaN's type & payload */ |
2122 | 0 | memcpy(&x, &v, sizeof(v)); |
2123 | 0 | return x; |
2124 | 0 | } |
2125 | 0 | } |
2126 | | |
2127 | 0 | x = (double)f / 1024.0; |
2128 | |
|
2129 | 0 | if (e == 0) { |
2130 | 0 | e = -14; |
2131 | 0 | } |
2132 | 0 | else { |
2133 | 0 | x += 1.0; |
2134 | 0 | e -= 15; |
2135 | 0 | } |
2136 | 0 | x = ldexp(x, e); |
2137 | |
|
2138 | 0 | if (sign) |
2139 | 0 | x = -x; |
2140 | |
|
2141 | 0 | return x; |
2142 | 0 | } |
2143 | | |
2144 | | double |
2145 | | PyFloat_Unpack4(const char *data, int le) |
2146 | 12 | { |
2147 | 12 | unsigned char *p = (unsigned char *)data; |
2148 | 12 | float x; |
2149 | | |
2150 | 12 | if ((_PY_FLOAT_LITTLE_ENDIAN && !le) || (_PY_FLOAT_BIG_ENDIAN && le)) { |
2151 | 12 | char buf[4]; |
2152 | 12 | char *d = &buf[3]; |
2153 | 12 | int i; |
2154 | | |
2155 | 60 | for (i = 0; i < 4; i++) { |
2156 | 48 | *d-- = *p++; |
2157 | 48 | } |
2158 | 12 | memcpy(&x, buf, 4); |
2159 | 12 | } |
2160 | 0 | else { |
2161 | 0 | memcpy(&x, p, 4); |
2162 | 0 | } |
2163 | | |
2164 | | /* return sNaN double if x was sNaN float */ |
2165 | 12 | if (isnan(x)) { |
2166 | 0 | uint32_t v; |
2167 | 0 | memcpy(&v, &x, 4); |
2168 | |
|
2169 | 0 | #ifndef __riscv |
2170 | 0 | if ((v & (1 << 22)) == 0) { |
2171 | 0 | double y = x; /* will make qNaN double */ |
2172 | 0 | uint64_t u64; |
2173 | 0 | memcpy(&u64, &y, 8); |
2174 | 0 | u64 &= ~(1ULL << 51); /* make sNaN */ |
2175 | 0 | memcpy(&y, &u64, 8); |
2176 | 0 | return y; |
2177 | 0 | } |
2178 | | #else |
2179 | | double y = x; |
2180 | | uint64_t u64; |
2181 | | |
2182 | | memcpy(&u64, &y, 8); |
2183 | | if ((v & (1 << 22)) == 0) { |
2184 | | u64 &= ~(1ULL << 51); |
2185 | | } |
2186 | | /* Workaround RISC-V, see PyFloat_Pack4() */ |
2187 | | if (v & (1 << 31)) { |
2188 | | u64 |= (1ULL << 63); /* set sign */ |
2189 | | } |
2190 | | /* add payload */ |
2191 | | u64 -= (u64 & 0x7ffffffffffffULL); |
2192 | | u64 += ((v & 0x3fffffULL) << 29); |
2193 | | |
2194 | | memcpy(&y, &u64, 8); |
2195 | | return y; |
2196 | | #endif |
2197 | 0 | } |
2198 | | |
2199 | 12 | return x; |
2200 | 12 | } |
2201 | | |
2202 | | double |
2203 | | PyFloat_Unpack8(const char *data, int le) |
2204 | 761 | { |
2205 | 761 | unsigned char *p = (unsigned char *)data; |
2206 | 761 | double x; |
2207 | | |
2208 | 761 | if ((_PY_FLOAT_LITTLE_ENDIAN && !le) || (_PY_FLOAT_BIG_ENDIAN && le)) { |
2209 | 60 | char buf[8]; |
2210 | 60 | char *d = &buf[7]; |
2211 | 60 | int i; |
2212 | | |
2213 | 540 | for (i = 0; i < 8; i++) { |
2214 | 480 | *d-- = *p++; |
2215 | 480 | } |
2216 | 60 | memcpy(&x, buf, 8); |
2217 | 60 | } |
2218 | 701 | else { |
2219 | 701 | memcpy(&x, p, 8); |
2220 | 701 | } |
2221 | | |
2222 | 761 | return x; |
2223 | 761 | } |