Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python 3.4 give the wrong answer for division of large numbers, and how can I test for divisibility? [duplicate]

In my program, I'm using division to test if the result is an integer, I'm testing divisibility. However, I'm getting wrong answers. Here is an example:

print(int(724815896270884803/61))

gives 11882227807719424.

print(724815896270884803//61)

gives the correct result of 11882227807719423.

Why is the floating point result wrong, and how can I test whether the large number is divisible by 61? Do I really need to do integer division and then multiply it back and see if it's equal?

like image 573
Zook Avatar asked Dec 14 '22 22:12

Zook


1 Answers

Instead of dividing, you should compute the modulus (%):

print(724815896270884803 % 61)

This is similar to doing an integer division and returning the remainder (think back to elementary school long division). A remainder of 0 means it is divisible.

like image 188
mhlester Avatar answered Dec 17 '22 12:12

mhlester