我希望有人可以帮我解释一下这个关于大除数的奇怪结果,或者建议我使用一些关键词,这样我就能得到更好的搜索。
>>> m = 1e9+9
>>> n = 1000000009
>>> m == n
True
>>> 2549015908609065 % m
885667930.0
>>> 2549015908609065 % n
885667930
>>> 2549015908609065L % n
885667930L
>>> 2549015908609065L % m
885667930.0
>>> 254901590860906524041412370460835L % m
98506080.0
>>> 254901590860906524041412370460835L % n
327998297L
>>> 254901590860906524041412370460835L % int(m)
327998297L
答案 0 :(得分:2)
您看到奇怪结果的原因是因为您在浮点数上执行模数,浮点数具有不精确的表示。 decimal模块上的文档很好地突出了这一点。
要对非常大的数字执行精确操作,可以使用十进制类,如下所示:
from decimal import *
print Decimal(2549015908609065) % Decimal(1e9) # Gives the answer you expect
答案 1 :(得分:1)
m = 1e9+9
将该数字存储为浮点数;但是n = 1000000009
将数字存储为整数。
当你用float分割整数时,python会隐式输出一个float作为结果;但是,当您将整数除以另一个整数时,您将获得整数商。 Float超过更大数字的精度会降低。
如果你注意到,
>>> 254901590860906524041412370460835L % m
98506080.0
#outputted a float with different precision
>>> 254901590860906524041412370460835L % n
327998297L
#outputted a long int
检查http://www.tutorialspoint.com/python/python_numbers.htm以获取有关python数字的基本教程