用梯度法程序求极小值点
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import math
from mpl_toolkits.mplot3d import Axes3D
import warnings
def hyj():
x1 = 0
x2 = 3
alpha = 0.001
iter_num = 1
def f2(x1, x2):
return (x1-2)**4 + (x1-2*x2)**2
def hx1(x1, x2):
return 4*(x1-2)**3+2*x1-4*x2
def hx2(x, y):
return 4*x2
GD_X1 = [x1]
GD_X2 = [x2]
GD_Y = [f2(x1,x2)]
y_change = f2(x1,x2)
while(y_change > 1e-10 and iter_num < 100) :
tmp_x1 = x1 - alpha * hx1(x1,x2)
tmp_x2 = x2 - alpha * hx2(x1,x2)
tmp_y = f2(tmp_x1,tmp_x2)
f_change = np.absolute(tmp_y - f2(x1,x2))
x1 = tmp_x1
x2 = tmp_x2
GD_X1.append(x1)
GD_X2.append(x2)
GD_Y.append(tmp_y)
iter_num += 1
print("极值点" ,(x1, x2))
print("极值" ,f2(x1,x2))
print(GD_X1)
print(GD_X2)
hyj()