在编程过程中,我注意到了math.exp(2)和math.e**2的结果有所不同。如下所示,当计算e^1时,这种差异并未出现。
作为一个经验不足的程序员,我想知道为什么会出现这种差异? 我猜测这可能与四舍五入有关。Python文档说
作为一个经验不足的程序员,我想知道为什么会出现这种差异? 我猜测这可能与四舍五入有关。Python文档说
math.exp(x)
返回e**x
,但这似乎不完全正确。那么为什么math.exp(x)
操作与math.e**x
不同呢?>>> math.exp(1)
2.718281828459045
>>> math.e**1
2.718281828459045
>>> math.exp(1)==math.e**1
True
>>> math.exp(2)
7.38905609893065
>>> math.e**2
7.3890560989306495
>>> math.exp(2)==math.e**2
False
>>> math.exp(100)
2.6881171418161356e+43
>>> math.e**100
2.6881171418161212e+43
>>> math.exp(100)==math.e**100
False
math.exp
是用c
(甚至是硬件)实现的,因此具有略微不同的浮点行为。 - tobias_kexp(x)
比e ** x
更精确。 - Mark Dickinson