0

Consider this code snippet.

>>> n, m = 10011617, 100000000000006340
>>> s = lambda n: n * (n + 1) / 2
>>> s(n)
50116242483153.0
>>> s(n) == int(s(n))
True
>>> m % s(n)
18096246116101.0
>>> m % int(s(n))
18096246116105

As you can see, s(n) is an integer (mathematically), yet m % s(n) != m % int(s(n)).

Could this have to do with s(n) or m being a long under the hood? Even if that's the case, why does s(n) == int(s(n)) yet when I take the modulus the results are not equal?

P.S. I ran this in repl.it

Daniel
  • 3,188
  • 14
  • 34

1 Answers1

2

In this particular case the problem is due more to m than s(n). When computing m % s(n), since s(n) is a float, m is coerced to a float. But -- float(m) loses precision. The clearest way to see this is that

m == 100000000000006340

but

int(float(m)) == 100000000000006336

Note that 100000000000006336 % 50116242483153 == 18096246116101, which shows where the mystery value comes from.

John Coleman
  • 51,337
  • 7
  • 54
  • 119