I was trying to calculate int((226553150*1023473145)/5.) using python and I got 46374212988031352 although it should be 46374212988031350.
-
1Why are you using floating point division just to cast to int afterwards? You can calculate `(226553150*1023473145)//5` directly and get the correct integer result. – tobias_k Jun 17 '16 at 21:53
-
Change your denominator from `5.` to `5`. – UltraInstinct Jun 17 '16 at 21:54
-
4In my opinion it's a question about integer arithmetic, not floating point math, so the duplicate may be questionable. – StefanS Jun 17 '16 at 21:54
-
@StefanS: Totally agreed. In fact the correct is: "Do not perform floating point division, stick to integers.", and not "Do not expect accurate answers when dealing with Floating point" (as in the dup) – UltraInstinct Jun 17 '16 at 21:57
-
@StefanS: I also agree. This question is certainly a duplicate of SOME other question (confusion over Python's division operator(s)), but not a duplicate of THAT question (about floating point arithmetic, specifically addition of decimals!). – John Y Jun 17 '16 at 22:09
1 Answers
Remove the period for integer division:
int((226553150*1023473145)/5)
Comes out as 46374212988031350 for me.
Edit after @tobias_k's comment:
This only works in Python2, where /
is either floating point division (if either of the arguments is float) or integer division (if both arguments are integers).
In Python3 (or with from __future__ import division
in Python2) /
is always floating point division and the rounding problem comes up again, because the numbers you multiply are too large to be exactly expressed in floating point.
The solution is either to use //
, which is always integer division in all Python versions or (if you really need the denominator to be float) to switch to mpmath, where you can increase the floating point precision until you don't have the rounding errors anymore.

- 1,740
- 14
- 20
-
1Only works with Python 2. In Python 3, `/` will default to floating point division. Better use `//`. Also, no need for `int(...)` – tobias_k Jun 17 '16 at 21:56
-
@tobias_k in `int(x/y)` the `int` matters if you don't use `//` although I agree that floor division is the correct way to go. – Tadhg McDonald-Jensen Jun 17 '16 at 22:09