4

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?

Zook
  • 499
  • 9
  • 20

2 Answers2

7

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.

mhlester
  • 22,781
  • 10
  • 52
  • 75
  • Oh wow I can't believe I missed that. Duh. I was shortcutting because I wanted to test whether the square root of the division was also an integer, and using `sqrt(724.../61)%1==0` – Zook May 27 '14 at 21:39
5

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
user2357112
  • 260,549
  • 28
  • 431
  • 505
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 1
    It's not true that both arguments are converted to float before the floating-point division is carried out: instead, Python computes a correctly-rounded division result using integer arithmetic internally (though historically, Python did do something along the lines of converting both ints to a float). The problem here is simply that the division result is not exactly representable as an IEEE 754 binary64 float. (Reference: http://bugs.python.org/issue1811.) – Mark Dickinson Feb 07 '16 at 19:55