就如文章标题所示,只是简单的代码整理,用于数模比赛的准备(虽然并没有用上)
算法的数学原理请查阅前人blog
牛顿法
代码
这里我演示的函数为
f ( x ) = x 1 2 + x 2 2 + 3 ∗ x 1 + 4 ∗ x 2 − 26 f(x)=x_1^2+x_2^2+3*x_1+4*x_2-26 f(x)=x12+x22+3∗x1+4∗x2−26
"""
Newton法
Rosenbrock函数
函数 f(x)
梯度 g(x)
hessen 矩阵
"""
# 一阶导
def jacobian(x):
return np.array([2*x[0]+3,2*x[1]+4])
# 二阶导
def hessian(x):
return np.array([[2,0],[0,2]])
def newton(x0):
print('初始点为:',x0)
W=np.zeros((2,10**3))
i = 1
imax = 1000
W[:,0] = x0
x = x0
delta = 1
while i<imax and delta>0.1:
p = -np.dot(np.linalg.inv(hessian(x)),jacobian(x))
print('jacobian: ',jacobian(x))
print('hessian: ',hessian(x))
x0 = x
x = x + p
W[:,i] = x
delta = sum((x-x0))
print('第'+