一、 数值微分
d f ( x ) d x = lim h → 0 f ( x + h ) − f ( x ) h \frac{\mathrm{d} f(x)}{\mathrm{d} x}= \lim_{h \to 0}\frac{f(x+h)-f(x)}{h} dxdf(x)=h→0limhf(x+h)−f(x)
求导公式表示瞬间的变化量,在python中可以定义为
def numerical_diff(f,x):
h = 10e - 50
return (f(x+h) - f(x)) / h
参数f代表函数,x代表自变量,想要h尽可能接近0,所以h使用了10e-50,但是这样反而会产生舍入误差。在python中舍入误差表示为
np.float32(1e-50) # 输出 0.0
无法正确的表示出来。但是最开始设定h=1e-50,(x+h)和x之间的斜率仍和真正的斜率之间是不一致的,因为h是人为设定,永远不可能无限接近于0。
所以可以计算(x+h)和(x-h)之间的差分,以x为中心,计算左右的差分,也叫中心差分。
def numerical_diff(f,x):
h = 1e-4 #0.01
return (f(x+h) - f(x-h)) / (2*h)
所以,利用微小的差分求导数的过程叫做数值微分(numerical differentiation)
d f ( x ) d x = lim h → 0 f ( x + h ) − f ( x − h ) 2 h \frac{\mathrm{d} f(x)}{\mathrm{d} x}= \lim_{h \to 0}\frac{f(x+h)-f(x-h)}{2h} dxdf(x)<