gpt4 book ai didi

python-2.7 - Mod 函数在 python 中对于大数失败

转载 作者:行者123 更新时间:2023-12-02 18:46:50 26 4
gpt4 key购买 nike

这段Python代码

for x in range(20, 50):
print(x,math.factorial(x),math.pow(2,x), math.factorial(x) % math.pow(2,x) )

计算到 x=22 为止的精度,但 x>22 时的 mod 始终为 0。

Wolframalpha 表示 x>22 的结果非零。例如,当 x=23我们得到 6815744。

我猜这个问题是由于 python 实际计算 mod 函数的方式造成的,但想知道是否有人真正知道。

最佳答案

您遇到了浮点限制; math.pow() 返回一个 float ,因此两个操作数都被强制转换为 float 。对于 x = 23math.factorial(x) 返回的整数大于 float 可以建模的整数:

>>> math.factorial(23)
25852016738884976640000
>>> float(math.factorial(23))
2.585201673888498e+22

右侧运算符是一个小得多的 float (只有 7 位),正是指数的差异导致了模运算符错误。

使用**来坚持整数:

for x in range(20, 50):
print(x, math.factorial(x), 2 ** x, math.factorial(x) % (2 ** x))

整数运算仅受限于可用内存量,对于 x = 23 会计算出正确的值,一直到 x = 49 都可以正常工作>:

>>> x = 23
>>> print(x, math.factorial(x), 2 ** x, math.factorial(x) % (2 ** x))
23 25852016738884976640000 8388608 6815744
>>> x = 49
>>> print(x, math.factorial(x), 2 ** x, math.factorial(x) % (2 ** x))
49 608281864034267560872252163321295376887552831379210240000000000 562949953421312 492581209243648

请注意,即使对于较小的浮点模数计算,您确实应该使用 math.fmod() function ,原因在文档中解释。然而,对于这种情况,它也失败了,同样是因为您超出了 float 学的限制:

>>> print(x, math.factorial(x), math.pow(2, x), math.fmod(math.factorial(x), math.pow(2, x)))
23 25852016738884976640000 8388608.0 0.0

关于python-2.7 - Mod 函数在 python 中对于大数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34384400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com