用拉格朗日乘子法求解帶約束最優化問題

2022-09-22 23:20:25 字數 1560 閱讀 2101

#

-*- coding: utf-8 -*-

#匯入sympy包,用於求導,方程組求解等等

from sympy import * #

設定變數

x1 = symbols("x1"

)x2 = symbols("x2"

)alpha = symbols("

alpha")

beta = symbols("

beta")

#構造拉格朗日等式

l = (x1-7/4)*(x1-7/4) + (x2-5/2)*(x2-5/2) + alpha*(5-x1-x2) + beta*(x1+x2*x2-5*x2) #

求導,構造kkt條件

difyl_x1 = diff(l, x1) #

對變數x1求導

difyl_x2 = diff(l, x2) #

對變數x2求導

difyl_beta = diff(l, beta) #

對乘子beta求導

dualcpt = alpha * (5-x1-x2) #

對偶互補條件

#求解kkt等式

aa =solve([difyl_x1, difyl_x2, difyl_beta, dualcpt], [x1, x2, alpha, beta]) #

列印結果,還需驗證alpha>=0,x1>=0,x2>=0和不等式約束<=0

for i in

aa:

if i[2]>=0 and i[0] >= 0 and i[1]>=0:

if (i[0]+i[1]-5) >=0:

print

(i)

'''output

(2.25000000000000, 4.50000000000000, 0.0, -1.00000000000000)

(4.00000000000000, 1.00000000000000, 2.62500000000000, -1.87500000000000)

(6.25000000000000, 2.50000000000000, 0.0, -9.00000000000000)

'''

求出的三個極點分別為目標圓與拋物線上半相切,與直線和拋物線相交,與拋物線頂點相切

其中(9/4,9/2)時取得極小值

參考:1.**拉格朗日乘子法

2.python科學計算利器——sympy庫

3.使用python求解帶約束的最優化問題詳解