Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 gives wrong output when dividing two large numbers?

a = 15511210043330985984000000  # (25!)
b = 479001600                   # (12!)
c = 6227020800                  # (13!)

On dividing ans = int(a/(b*c)) or ans = int((a/b)/c) we get ans equal to 5200299 instead of 5200300

like image 655
Yash Agarwal Avatar asked Dec 04 '22 06:12

Yash Agarwal


2 Answers

In Python 3.x / means floating point division and can give small rounding errors. Use // for integer division.

ans = a // (b*c)
like image 158
Mark Byers Avatar answered Dec 26 '22 20:12

Mark Byers


Try using integer division instead of float division.

>>> 15511210043330985984000000 / (479001600 * 6227020800)
5200299.999999999
>>> 15511210043330985984000000 // (479001600 * 6227020800)
5200300
like image 44
Ignacio Vazquez-Abrams Avatar answered Dec 26 '22 18:12

Ignacio Vazquez-Abrams