数值梯度的计算

147 篇文章 19 订阅
103 篇文章 8 订阅

数值梯度的表达式:

\frac{f(x+h) - f(x)}{h}

其误差为O(h),证明如下:

f(x+h)=f(x)+f'(x)h+O(h^2)

\frac{f(x+h) - f(x)}{h}=\frac{f(x)+f'(x)h+O(h^2)-f(x)}{h} = f'(x) - O(h)

 而:

  \frac{f(x+h) - f(x-h)}{2h}

f(x+h)=f(x)+f'(x)h+f''(x)h^2+O(h^3)

f(x-h)=f(x)-f'(x)h+f''(x)h^2-O(h^3)

\frac{f(x+h) - f(x-h)}{2h}=\frac{2f'(x)h + 2O(h^3)}{2h}=f'(x)+O(h^2)

的误差是O(h^2),  这是不同的地方。

以函数

f(x)=0.01x^2 + 0.1x

为例,计算它的数值微分,首先根据高等数学公式,可以得出f'(x)=0.02x + 0.1

f'(5)=0.2

# coding: utf-8
import numpy as np
import matplotlib.pylab as plt

def numerical_diff(f, x):
    h = 1e-3 # 0.001
    return (f(x+h) - f(x-h)) / (2*h)

def function_1(x):
    return 0.01*x**2 + 0.1*x 

def tangent_line(f, x):
    d = numerical_diff(f, x)
    print(d)
    y = f(x) - d*x
    return lambda t: d*t + y
     
x = np.arange(0.0, 20.0, 0.1)
y = function_1(x)
plt.xlabel("x")
plt.ylabel("f(x)")

tf = tangent_line(function_1, 5)
y2 = tf(x)

plt.plot(x, y)
plt.plot(x, y2)
plt.show()

运行结果如下:


结束

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

papaofdoudou

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值