Reputation: 13
I tried:
>>> int(5 * 1000000000000000000 * 10 ** 9 / 1000)
5000000000000000452984832
Why I am not getting
5000000000000000000000000
How do I obtain the real result?
Upvotes: 1
Views: 58
Reputation: 36
I think this issue is likely due to the floating point arithmetic python uses. From python's documentation:
On most machines today, floats are approximated using a binary fraction with the numerator using the first 53 bits starting with the most significant bit and with the denominator as a power of two.
This basically explains that the extra numbers you have are just a result of the way machines store floats. The solution to this is likely to just be mindful of this effect when you work with particularly large numbers.
Upvotes: 1
Reputation: 506
It's because in python Division operator /
, implicitly converts the operands to float and does the division and returns the quotient in float as well, even if both the operands are integers. This can be seen from the result of the division
As you can see the division returns a float which is stored with some precision in the machine's memory and when converting that to integer you get the arbitrary values at the end of the quotient.
One remedy that which you can use is, using floor division //
which returns an integer itself as a result. Therefore you need not convert it back to integer explicitly.
Upvotes: 1
Reputation: 11332
>>> (5 * 1000000000000000000 * 10 ** 9 // 1000)
5000000000000000000000000
As soon as you use / instead of //, you're using double precision floating point. You get about 53-bits of precision, or about 16-bits of decimal precision.
There is no way to precisely represent 5000000000000000000000000 in double precision floating point. You're getting the closest integer that can be represented precisely.
Upvotes: 2