I'm trying to execute next code int((226553150 * 1023473145) / 5)
and python3 gives me an answer 46374212988031352
. But ruby and swift give me an answer 46374212988031350
.
What do I miss?
You are missing that Python's division (from Python 3 on) is by default a float division, so you have reduced precision in that. Force the integer division by using //
instead of /
and you will get the same result.
a / b
is a floating-point division in Python 3. In order to perform integer division you should use //
operator:
In [3]: (226553150 * 1023473145) // 5
Out[3]: 46374212988031350
Floating point division precision limited to the mantissa size:
In [19]: (226553150 * 1023473145) / 5
Out[19]: 4.637421298803135e+16
As you can see, Python correctly represents all digits but the last. You could also made some interesting tricks with it:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With