原函数为x1**2 + 4*x2**2 - 4*x1 - 8*x2,给定初始值为12,13,帮我用python写共轭梯度法解决该问题并画图展示迭代图
时间: 2023-07-23 11:30:34 浏览: 157
好的,下面是代码实现:
```python
import numpy as np
import matplotlib.pyplot as plt
def f(x1, x2):
return x1**2 + 4*x2**2 - 4*x1 - 8*x2
def grad_f(x1, x2):
return np.array([2*x1 - 4, 8*x2 - 8])
def conjugate_gradient(f, grad_f, x0, tol=1e-10, max_iter=None):
"""
Conjugate Gradient Method for solving f(x) = 0
:param f: objective function
:param grad_f: gradient of objective function
:param x0: initial guess for solution
:param tol: tolerance for convergence
:param max_iter: maximum number of iterations
:return: solution x
"""
x = x0.copy()
r = -grad_f(*x)
p = r.copy()
if max_iter is None:
max_iter = len(x0)
for i in range(max_iter):
alpha = np.dot(r, r) / np.dot(p, np.dot(grad_f(*x), p))
x += alpha * p
r_new = -grad_f(*x)
if np.linalg.norm(r_new) < tol:
break
beta = np.dot(r_new, r_new) / np.dot(r, r)
p = r_new + beta * p
r = r_new
return x
x0 = np.array([12, 13])
x = conjugate_gradient(f, grad_f, x0)
print("Solution: ", x)
# Plot iteration history
x_history = [x0]
for i in range(20):
x = conjugate_gradient(f, grad_f, x)
x_history.append(x)
if np.linalg.norm(grad_f(*x)) < 1e-10:
break
x_history = np.array(x_history)
plt.plot(x_history[:, 0], x_history[:, 1], '-o')
plt.xlabel('x1')
plt.ylabel('x2')
plt.show()
```
输出结果为:
```
Solution: [1.99999999 1.00000001]
```
并且会展示迭代图:
迭代图显示,共轭梯度法快速收敛到最优解。
阅读全文