我使用以下函数来近似函数在某一点的导数:
def prime_x(f, x, h):
if not f(x+h) == f(x) and not h == 0.0:
return (f(x+h) - f(x)) / h
else:
raise PrecisionError
作为一个测试我正在通过f
as fx
and x
如3.0。在哪里fx
is:
def fx(x):
import math
return math.exp(x)*math.sin(x)
其中有exp(x)*(sin(x)+cos(x))
作为衍生品。现在,根据谷歌和我的计算器
exp(3)*(sin(3)+cos(3)) = -17.050059
.
到目前为止,一切都很好。但是当我决定用小值测试该函数时h
我得到以下信息:
print prime_x(fx, 3.0, 10**-5)
-17.0502585578
print prime_x(fx, 3.0, 10**-10)
-17.0500591423
print prime_x(fx, 3.0, 10**-12)
-17.0512493014
print prime_x(fx, 3.0, 10**-13)
-17.0352620898
print prime_x(fx, 3.0, 10**-16)
__main__.PrecisionError: Mantissa is 16 digits
为什么当 h 减小时(在某个点之后)误差会增大?我本来期待相反的情况,直到f(x+h)
等于f(x)
.