通常在数值计算中,执行一个计算任务并不像你在纸上做的那样好。主要是因为你必须关注浮点错误。因此,衍生工具的更好实现方法如下:def derivative(func, x, h = None):
if h is None:
# Note the hard coded value found here is the square root of the
# floating point precision, which can be found from the function
# call np.sqrt(np.finfo(float).eps).
h = 1.49011611938477e-08
xph = x + h
dx = xph - x
return (func(xph) - func(x)) / dx
通过观察这个,你可能会反对并说dx = h,因为xph - x = x + h - x = h,但是如果你真的在计算机上计算,你会发现这不是真的,因为四舍五入。还要注意,为h选择一个好的值是很重要的,以获得可能的最佳结果。现在,对于python中的浮点,默认值设置为机器精度的平方根。在