Mod函数在python中失败大量 [英] Mod function fails in python for large numbers

查看:106
本文介绍了Mod函数在python中失败大量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此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始终为0时的mod.

calculates fine up to x=22 but the mod when x>22 is always 0.

Wolframalpha说x> 22的结果为非零. 例如,当 x = 23 时,我们得到6815744.

Wolframalpha says the results for x>22 are nonzero. For example, when x=23 we get 6815744.

我想这个问题是由python实际计算mod函数的方式导致的,但我想知道是否有人真正知道过.

I guess this problem results from how python actually calculates the mod function but was wondering if anyone actually knew.

推荐答案

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

You are running into floating point limitations; math.pow() returns a floating point number, so both operands are coerced to floats. For x = 23, math.factorial(x) returns an integer larger than what a float can model:

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

右侧的运算符是一个较小的浮点数(仅7位数字),正是指数的不同导致了模数运算符的错误.

The right-hand-side operator is a much smaller floating point number (only 7 digits), it is that difference in exponents that causes the modulus operator error out.

使用**坚持整数:

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

整数操作仅限于可用的内存量,并且对于x = 23,将计算正确的值,并一直正常工作直至x = 49:

Integer operations are only limited to how much memory is available, and for x = 23 the correct value is calculated, continuing to work correctly all the way to 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

请注意,即使对于较小的浮点模数计算,您实际上也应该使用

Note that for even for smaller floating point modulus calculations, you really should be using the math.fmod() function, for reasons explained in the documentation. It too fails for this case however, again because you are reaching beyond the limits of floating point math:

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

这篇关于Mod函数在python中失败大量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆