Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

math - Strange Python 3 mod behavior for longs

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

question from:https://stackoverflow.com/questions/65893744/strange-python-3-mod-behavior-for-longs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...