python里面mod函数,Mod函数在Python中失败大量

This python code

for x in range(20, 50):

print(x,math.factorial(x),math.pow(2,x), math.factorial(x) % math.pow(2,x) )

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

Wolframalpha says the results for x>22 are nonzero.

For example, when x=23 we get 6815744.

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

解决方案

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

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.

Use ** to stick to integers:

for x in range(20, 50):

print(x, math.factorial(x), 2 ** x, math.factorial(x) % (2 ** x))

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值