Python 3 long ints and multiplications

I am trying to execute the following code int((226553150 * 1023473145) / 5)and python3 gives me the answer 46374212988031352. But ruby ​​and quickly give me an answer 46374212988031350.

What am I missing?

+4
source share
2 answers

You are missing the fact that Python partitioning (from Python 3 on) is the default float section, so you have reduced precision in this. Force integer division using //instead /, and you will get the same result.

+7
source

a / bis a floating point division in Python 3. To perform integer division, you must use the operator //:

In [3]: (226553150 * 1023473145) // 5
Out[3]: 46374212988031350

Floating point accuracy is limited by the size of the mantissa:

In [19]: (226553150 * 1023473145) / 5
Out[19]: 4.637421298803135e+16

, Python , . :

In [20]: int((226553150 * 1023473145) / 5)
Out[20]: 46374212988031352

In [21]: int((226553150 * 1023473145) / 5 - 1)
Out[21]: 46374212988031352

In [22]: int((226553150 * 1023473145) / 5 + 1)
Out[22]: 46374212988031352

In [23]: int((226553150 * 1023473145) / 5 - 2)
Out[23]: 46374212988031352

In [24]: int((226553150 * 1023473145) / 5 - 3)
Out[24]: 46374212988031352

In [25]: int((226553150 * 1023473145) / 5 - 4)
Out[25]: 46374212988031344

In [26]: int((226553150 * 1023473145) / 5 + 4)
Out[26]: 46374212988031360

In [27]: int((226553150 * 1023473145) / 5 + 3)
Out[27]: 46374212988031352
+5

Source: https://habr.com/ru/post/1629927/