= -6ren">
gpt4 book ai didi

python - 如果整数没有最大值,为什么 1e100+1 == 1e100?

转载 作者:行者123 更新时间:2023-12-03 18:45:02 28 4
gpt4 key购买 nike

考虑这段代码:

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

我不明白为什么需要检查 n+1 == n

我认为 Python 中的整数没有最大值,那么为什么要例如 1e100+1 == 1e100

最佳答案

1e100 不是 int;它是一个float,所以它的精度有限,对于很大的数字,精度太低而无法表示1e1001e100 + 1 之间的差异>.

>>> type(1e100)
<class 'float'>

如果你想把这个数字作为一个int,你可以写成10 ** 100。然后,您将得到预期的结果,因为 Python 的 int 类型允许任意大的整数。

>>> x = 10 ** 100
>>> y = 10 ** 100 + 1
>>> x
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
>>> y
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
>>> x == y
False

关于python - 如果整数没有最大值,为什么 1e100+1 == 1e100?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60109329/

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