求导,梯度
- 高等数学中一个函数 y = f ( x ) y = f(x) y=f(x)
- 假设这个函数表示求出速度 , y ( 速度 k m / h ) = 1000 ( m ) x ( 小时 h ) y(速度km/h) = \frac{1000(m)}{x(小时 h)} y(速度km/h)=x(小时h)1000(m)
- 那么这里的求导就是一个求出加速度 p p p
- p = f ′ ( x ) = ( 1000 x ) ′ = − 1000 x 2 p = f^{'}(x) = (\frac{1000}{x})^{'} = -\frac{1000}{x^2} p=f′(x)=(x1000)′=−x21000
- 这里的求导直接使用了
牛顿莱布尼茨公式
- 而代码的办法是逼近求导
代码实现
- 设 y = f ( x ) y = f(x) y=f(x)
- 根据最基础的求导理解,逼近 p = lim n − > 0 f ( x + n ) − f ( x ) n p = \lim_{n->0}\frac{f(x+n)-f(x)}{n} p=limn−>0nf(x+n)−f(x)
- 那么求导代码如下
def func(x):return 1000 / x
# 求导数
def get_p(x, batch=5, init=0.1, step=0.1):for i in range(batch):result = (func(x + init) - func(x)) / initinit = init * stepprint(f"result == {result} batch = {i} init = {init}")return result
# 根据极限逼近公式计算
print(get_p(1))
# 根据莱布尼茨公式计算
print(-1000 / (1**2))