本题测试函数为 :
f = x1 ** 4 + x2 ** 2 - 2 * x1 - 4 * x1 * x2
import sympy as sy
def cal_dffi(f, a, b):
x1 = sy.symbols("x1")
x2 = sy.symbols("x2")
f1 = sy.diff(f, x1)
y1 = f1.evalf(subs={x1: a, x2: b})
f2 = sy.diff(f, x2)
y2 = f2.evalf(subs={x1: a, x2: b})
return y1, y2
def gd(a, b, f, alpha, detal):
x1 = sy.symbols("x1")
x2 = sy.symbols("x2")
y0 = f.evalf(subs={x1: a, x2: b})
while True:
detalx, detaly = cal_dffi(f, a, b)
a = a - alpha * detalx
b = b - alpha * detaly
y1 = f.evalf(subs={x1: a, x2: b})
if abs(y1 - y0) < detal:
break
else:
y0 = y1
print('x1:', a, 'x2:', b, '极小值:', y1)
return a, b, y1
if __name__ == '__main__':
x1 = sy.symbols("x1")
x2 = sy.symbols("x2")
f = x1 ** 4 + x2 ** 2 - 2 * x1 - 4 * x1 * x2
a = 1
b = 1
alpha = 0.1
detal = 0.4 #
a, b, y = gd(a, b, f, alpha, detal)
print("x1,x2,f极小值分别为", a, b, y)
结果为:
x1: 1.20000000000000 x2: 1.20000000000000 极小值: -4.64640000000000
x1: 1.18880000000000 x2: 1.44000000000000 极小值: -5.15422532631921
x1: 1.29277352837120 x2: 1.62752000000000 极小值: -5.55966346025714
x1,x2,f极小值分别为 1.27955549763458 1.81912541134848 -5.87995367120089