線性規劃 大M法

2021-10-05 19:43:48 字數 3895 閱讀 9503

大m法其實就是單純形法,只不過稍稍加了一點改動,用來解決線性規劃標準型中存在人工變數的問題。

import numpy as np

#單純形法--大m法

# min z = -3x1 + x2 + x3

# x1 - 2x2 + x3 <= 11

# -4x1 + x2 + 2x3 >= 3

# -2x1 + x3 = 1

# x1 , x2, x3 >= 0

defgetvarnum

(b):

#得到鬆弛變數、剩餘變數、人工變數的總個數

number =

0#這裡我針對例子只判斷了<=、=、>= 3種型別,其實還可以新增別的約束條件型別

for bi in b:

if bi[-2

]=='<='

: number +=

1if bi[-2

]=='>='

: number +=

2if bi[-2

]=='=':

number +=

1return number

defgetsimtable

(z,b,m,varnumber)

:#得到初始單純形表的所有資訊

lengthz =

len(z)

a =cb =

xb =

for i in

range

(len

(b))

:if b[i][-

2]=='<='

: lengthz +=

1 z +=[0

] ai =[0

for j in

range

(varnumber)

]if i !=0:

for aa in a:if-

1in aa:

ai[i]=0

ai[i +1]

=1break

else

: ai[i]=1

else

: ai[i]=1

0)elif b[i][-

2]=='>='

: lengthz +=

2 z +=[0

, m]

ai =[0

for j in

range

(varnumber)

] ai[i]=-

1 ai[i +1]

=1elif b[i][-

2]=='='

: lengthz +=

1 z +=

[m] ai =[0

for j in

range

(varnumber)

]if i !=0:

for aa in a:if-

1in aa:

ai[i]=0

ai[i +1]

=1break

else

: ai[i]=1

else

: ai[i]=1

m = np.zeros(

(len

(b), lengthz +1)

) c = z +[0

]for i in

range

(len

(b))

: m[i]

= b[i][:

-2]+ a[i]

+[b[i][-

1]]return m,cb,c,xb

m =100000

#大m,乙個足夠大的正數

z =[-3

,1,1

]b =[[

1,-2

,1,'<=',11

],[-

4,1,

2,'>=',3

],[-

2,0,

1,'=',1]

]varnum = getvarnum(b)

m,cb,c,xb = getsimtable(z,b,m,varnum)

#初始單純形表資訊

cminusz =

judge =

false

while

not judge:

for i in

range

(m.shape[1]

-1):

cz =

0for j in

range

(m.shape[0]

):cz += m[j]

[i]* cb[j]

- cz)

ifmin

(cminusz)

>=0:

#判斷是否已得到最終單純形表

judge =

true

break

else

: xin = cminusz.index(

min(cminusz)

)#換入變數,目標函式為求最小值,因此這裡用min方法

minval =

float

("inf"

) infinite =

true

for i in

range

(m.shape[0]

):if m[i]

[xin]!=0

:if m[i][-

1]/ m[i]

[xin]

< minval and m[i][-

1]/ m[i]

[xin]

>0:

minval = m[i][-

1]/m[i]

[xin]

xout = i #換出變數

infinite =

false

if infinite is

true

:print

("問題無界"

) exit(

) m[xout]

= m[xout]

/ m[xout]

[xin]

for i in

range

(m.shape[0]

):if i != xout and m[i]

[xin]!=0

: m[i]

-= m[xout]

* m[i]

[xin]

cb[xout]

= c[xin]

#更新cb與xb

xb[xout]

= xin +

1 cminusz =

solution =[0

for i in

range

(m.shape[1]

-1)]

for i in

range

(len

(xb)):

solution[xb[i]-1

]= m[i][-

1]print

("最優解:"

+str

(solution)

)print

("目標函式最小值:"

+str(-

3* solution[0]

+ solution[1]

+ solution [2]

))

UOJ 179 線性規劃 線性規劃

這是一道模板題。這個題現在標程掛了。哪位哥哥願意提供一下靠譜的標程呀?本題中你需要求解乙個標準型線性規劃 有 nn 個實數變數 x1,x2,xn x1,x2,xn 和 m m 條約束,其中第 i i 條約束形如 nj 1aijxj bi j 1naijxj bi。此外這 n n 個變數需要滿足非負性...

UOJ 179 線性規劃 線性規劃

這是一道模板題。這個題現在標程掛了。哪位哥哥願意提供一下靠譜的標程呀?本題中你需要求解乙個標準型線性規劃 有 nn 個實數變數 x1,x2,xn x1,x2,xn 和 m m 條約束,其中第 i i 條約束形如 nj 1aijxj bi j 1naijxj bi。此外這 n n 個變數需要滿足非負性...

非線性規劃

1.基本形式和求解模式。2.掌握凸函式和凸規劃的概念及性質。3.掌握0.618法。4.無約束優化的最優性質,熟練運用最速下降法和共軛方法。約束最優化的性質,懲罰函式。minf x s.t gi x 0 i 1,2,ph j x 0,j 1,2 q可行域為 x x r n gi x 0,i 1,2,p...