Skip to content Skip to sidebar Skip to footer

Why Does Python 3.4 Give The Wrong Answer For Division Of Large Numbers, And How Can I Test For Divisibility?

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(72481589627088480

Solution 1:

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.

Solution 2:

The floating-point result is wrong because dividing two ints with / produces a float, and the exact result of your division cannot be represented exactly as a float. The exact result 11882227807719423 must be rounded to the nearest representable number:

In [1]: float(11882227807719423)
Out[1]: 1.1882227807719424e+16

Post a Comment for "Why Does Python 3.4 Give The Wrong Answer For Division Of Large Numbers, And How Can I Test For Divisibility?"