When I execute this python code:
integer = 18243150071292141317265306851
print(int(integer / 1))
The output I receive is: 18243150071292140668971909120
which does not equal to integer
.
Why does this happen and how can I make the output equal to integer
?
That result happens in Python 3 (or Python 2 with true division imported from __future__
), but not Python 2 in stock mode.
In Python 3, the operator /
does "true" division (with a fractional part), but to be able to represent a fractional part, the result has to be a float
(which is the same as double
in C). And since float
has only 53 significant binary digits (guessing your platform is IEEE754
based, as >99% are), the result has to be rounded to the nearest representable value, which is 18243150071292140668971909120.0.
Then, conversion back to int
(that is exact and essentially unlimited) gives the same value and you see it printed.
To get what you expect, use //
instead of /
: "floor division" on two ints produces an int. (OTOH, if any of the arguments are already float
, it can convert all arguments to perform floating division and then give you the floor as a float.)
This is essentially the same thing @PM2Ring said, but posted as an answer.
If you want to do calculations with not-only-integer numbers with precision more than a usual float
provides, you should get out of intrinsic types and consider using decimal
from the standard library, GMP
library wrapper or a similar solution.