參考https://www.youtube.com/watch?v=cXHvC_FGx24
目標方程式為四元(x1, x2, x3, x4)非線性方程式x1*x4*(x1+x2+x3)+x3。有兩條約束式,變數範圍1到5。求解滿足約束方程式的目標方程式最大值。
代碼:
# -*- coding: utf-8 -*-
import numpy as np
from scipy.optimize import minimize
def objective(x):
x1, x2, x3, x4 = x
return x1*x4*(x1+x2+x3)+x3
def constraint1(x):
x1, x2, x3, x4 = x
return x1*x2*x3*x4-25
def constraint2(x):
x1, x2, x3, x4 = x
return 40 - x1**2 - x2**2 - x3**2 - x4**2
bnds = ((1, 5), (1, 5), (1, 5), (1, 5))
con1 = {'type':'ineq', 'fun':constraint1}
con2 = {'type':'eq', 'fun':constraint2}
x0 = [1, 5, 5, 1]
sol = minimize(objective, x0, bounds = bnds, constraints=[con1, con2], tol=1e-6, options = {'maxiter':100, 'disp':True})
print(sol)
(圖一)優化結果 |
其中 x1, x3, x3, x4 = [1. , 4.7429961 , 3.82115462, 1.37940765],
最小值為17.01401724563517
沒有留言:
張貼留言