x = 1.5 * 10 ** 156
print(x * x)
print(x ** 2)
x * x
和x ** 2
在数学上是等价的。但是当x
很大时,前者可能返回inf
的结果,而后者会引发溢出错误。
inf
Traceback (most recent call last):
File "C:\Users\diana\miniconda3\envs\py37\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 3, in <module>
OverflowError: (34, 'Result too large')
为什么会这样呢?
x
转换为整数会得到正确的值。 - undefinedx
创建为一个整数,而不是从浮点数转换为整数。例如,尝试int(1.5*10**156) == 15*10**155
- 结果是False。或者执行print(int(1.5*10**156))
来查看中间浮点数的有限精度的影响。 - undefinedmath.nextafter(math.sqrt(sys.float_info.max), math.inf)
。 - undefined