Python 3 gives wrong output when dividing two large numbers?
In Python 3.x /
means floating point division and can give small rounding errors. Use //
for integer division.
ans = a // (b*c)
Try using integer division instead of float division.
>>> 15511210043330985984000000 / (479001600 * 6227020800)
5200299.999999999
>>> 15511210043330985984000000 // (479001600 * 6227020800)
5200300
Your problem (not using integer arithmetic) has been swept under your carpet for you by Python 3.2:
Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 15511210043330985984000000 / (479001600 * 6227020800)
5200300.0
>>> repr(15511210043330985984000000 / (479001600 * 6227020800))
'5200300.0'
>>> int(15511210043330985984000000 / (479001600 * 6227020800))
5200300
Python 3.1.3 (r313:86834, Nov 27 2010, 18:30:53) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 15511210043330985984000000 / (479001600 * 6227020800)
5200299.999999999
>>> repr(15511210043330985984000000 / (479001600 * 6227020800))
'5200299.999999999'
>>> int(15511210043330985984000000 / (479001600 * 6227020800))
5200299
I'm puzzled: presumably you used int()
because you realised that it was producing a float
answer. Why did you not take the (obvious?) next step of rounding it, e.g.
[3.1.3]
>>> int(round(15511210043330985984000000 / (479001600 * 6227020800)))
5200300
?