考虑下面的代码:
def factorial(n):
import math
if not n >= 0:
raise ValueError("n must be >= 0")
if math.floor(n) != n:
raise ValueError("n must be exact integer")
if n+1 == n: # catch a value like 1e300
raise OverflowError("n too large")
result = 1
factor = 2
while factor <= n:
result *= factor
factor += 1
return result我不明白为什么需要check n+1 == n。
我认为Python中的整数没有最大值,那么为什么例如1e100+1 == 1e100
发布于 2020-02-07 16:08:58
1e100不是int;它是float,所以它的精度是有限的,对于这么大的数字,精度太低,不能表示1e100和1e100 + 1之间的区别。
>>> type(1e100)
<class 'float'>如果你想把这个数字作为int,你可以写成10 ** 100。然后,假设Python的int类型允许任意大的整数,您将获得预期的结果。
>>> x = 10 ** 100
>>> y = 10 ** 100 + 1
>>> x
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
>>> y
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
>>> x == y
Falsehttps://stackoverflow.com/questions/60109329
复制相似问题