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