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