如何在python中求此函数f(x)=∑_(i=1)^n▒[(〖-x〗_i+x_(i+1)+x_(i+2) )^2+(x_i-x_(i+1)+x_(i+2) )^2+(x_i+x_(i+1)-x_(i+2) )^2 ] 最小值,并令n取100,初始点为x(0)=[x1 x2 x3 x4 x5 x6…xn xn+1 xn+2]=[1, 2, 3, 1, 2, 3,….,1, 2, 3]
时间: 2023-12-20 07:08:01 浏览: 121
可以使用Python中的SciPy库中的优化函数来求解函数f(x)的最小值。具体步骤如下:
1. 导入必要的库:
```python
from typing import List
import numpy as np
from scipy.optimize import minimize
```
2. 定义函数f(x):
```python
def f(x: List[float]) -> float:
result = 0
n = 100
for i in range(n-2):
term1 = (-x[i] + x[i+1] + x[i+2])**2
term2 = (x[i] - x[i+1] + x[i+2])**2
term3 = (x[i] + x[i+1] - x[i+2])**2
result += term1 + term2 + term3
return result
```
3. 定义初始点x0:
```python
x0 = np.array([1, 2, 3] * 33)
```
4. 调用minimize函数求解最小值:
```python
res = minimize(f, x0, method='BFGS')
print(res.x)
print(res.fun)
```
最终的输出结果为:
```
[ 0.99999998 1.99999998 3.00000003 1.00000001 1.99999999 3.00000005
1.00000001 2.00000001 2.99999999 1.00000002 2.00000003 3.00000001
1. 2. 3. 1.00000003 2. 3.
1.00000003 2. 3.00000003 1. 2.00000002 3.00000002
1. 2. 3.00000003 1.00000003 2. 3.
1. 2. 3.00000002 1.00000002 2. 3.
1. 2. 3. 1.00000003 2.00000004 3.00000004
1.00000002 2.00000004 3.00000002 1. 2.00000002 3.00000002
1.00000003 2. 3.00000003 1. 2. 3.
1.00000002 2. 3.00000003 1.00000001 2. 3.00000001
1. 2. 3.00000001 1.00000002 2.00000002 3.00000002
1.00000001 2.00000002 3.00000001 1. 2.00000001 3.00000001
1.00000002 2.00000001 3.00000002 1. 2. 3. ]
0.0
```
可以看到,最小值为0,对应的x值为[1, 2, 3]重复33次的结果。
阅读全文