[issue36934] C API Function PyLong_AsDouble Returning Wrong Value
New submission from Farhan Sajjad : Found this rather obscure behavior where certain 64 bit numbers are changing (probably losing precision somewhere down the call chain) if converted from PyLong to double using the PyLong_AsDouble C API function. TO REPRODUCE: #define __SIZEOF_STRS__ 512 static PyObject* test_pylong(PyObject* self, PyObject* args) { char rBuffer[__SIZEOF_STRS__]; char* strValue; if (!PyArg_ParseTuple(args, "s", &strValue)) return NULL; { printf("%s AS INGRESS\n", strValue); double dblValue = PyLong_AsDouble( PyLong_FromString(strValue, NULL, 10)); snprintf(rBuffer, __SIZEOF_STRS__, "%.0f", PyLong_AsDouble(PyLong_FromString(strValue, NULL, 10))); printf("CONVERT 1: %.0f\nCONVERT 2: %s\n", dblValue, rBuffer); } Py_RETURN_NONE; } Test: >>> test_pylong("1639873214337061279") 1639873214337061279 AS INGRESS CONVERT 1: 1639873214337061376 CONVERT 2: 1639873214337061376 -- messages: 342619 nosy: sajjadfx priority: normal severity: normal status: open title: C API Function PyLong_AsDouble Returning Wrong Value type: behavior versions: Python 3.7 ___ Python tracker <https://bugs.python.org/issue36934> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue36934] C API Function PyLong_AsDouble Returning Wrong Value
Farhan Sajjad added the comment: Thanks for your input Tim. Here is what I understand: 1. In Python 3, int can be arbitrarily large. 2. C double data type can hold very large numbers, and the number tested here is quite small compared to the max. It even fits fine in a long long int. 3. Quite interestingly, this function/conversion works in Python 2. >>> sys.float_info sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1) -- ___ Python tracker <https://bugs.python.org/issue36934> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue36934] C API Function PyLong_AsDouble Returning Wrong Value
Farhan Sajjad added the comment: Maybe I need to go back and understand why this loss of precision is taking place for the int->float conversion, and why for certain numbers. Also, it does not work in Python 2. Please disregard the previous message. -- resolution: -> not a bug stage: -> resolved status: open -> closed ___ Python tracker <https://bugs.python.org/issue36934> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com