Python裡面的scipy庫如何計算線性規劃問題呢?
就比如解決上述問題,在scipy裡面應該調用哪些函數呢?
pulp試試這個模塊。(以下採用python 3.5)
from pulp import *
# 設置對象
f = LpProblem(lptest, LpMinimize)
# 設置三個變數,並設置變數最小取值
x = LpVariable(x, lowBound = 0)
y = LpVariable(y, lowBound = 0)
z = LpVariable(z, lowBound = 0)
# 載入約束變數
f += 3.05 * x + 4.05 * y + 6.1 * z &>= 7.9
# 求解
GLPK().solve(f)
# 顯示結果
for i in f.variables():
print(i.name + "=" + str(i.varValue))
顯示如下:
GLPSOL: GLPK LP/MIP Solver, v4.55
Parameter(s) specified in the command line:
--cpxlp C:Users onyAppDataLocalTemp12100-pulp.lp -o C:Users onyAppDataLocalTemp12100-pulp.sol
Reading problem data from C:Users onyAppDataLocalTemp12100-pulp.lp...
1 row, 4 columns, 3 non-zeros
8 lines were read
GLPK Simplex Optimizer, v4.55
1 row, 4 columns, 3 non-zeros
Preprocessing...
1 row, 3 columns, 3 non-zeros
Scaling...
A: min|aij| = 3.050e+000 max|aij| = 6.100e+000 ratio = 2.000e+000
Problem data seem to be well scaled
Constructing initial basis...
Size of triangular part is 1
0: obj = 0.000000000e+000 infeas = 7.900e+000 (0)
* 1: obj = 0.000000000e+000 infeas = 0.000e+000 (0)
OPTIMAL LP SOLUTION FOUND
Time used: 0.0 secs
Memory used: 0.0 Mb (36952 bytes)
Writing basic solution to C:Users onyAppDataLocalTemp12100-pulp.sol...
1
__dummy=None
x=0.0
y=0.0
z=1.29508
scipy里有個linprog模塊做線性規劃,先進行參數設置再做優化。
from scipy.optimize import linprog
c = [1,1,1]
A = [[3.05, 4.05, 6.1]]
b = [[7.9]]
x_bounds = (0, None)
y_bounds = (0, None)
z_bounds = (0, None)
res = linprog(c, A_ub=A, b_ub=b, bounds=(x_bounds, y_bounds, z_bounds),
... options={"disp": True})
優化:
Optimization terminated successfully.
Current function value: -0.000000
Iterations: 0
結果:
fun: -0.0
message: Optimization terminated successfully.
nit: 0
slack: array([ 7.9])
status: 0
success: True
x: array([ 0., 0., 0.])
想問一下有沒有做整數規劃的包在python中,找了半天找不到!
import numpy as np
from scipy.optimize import linprog
a = np.array([1, 1, 1])
b = np.array([-7.9])c = np.array([[-3.05, -4.05, -6.1]])res = linprog(a, A_ub=c, b_ub=b)print(res)
這樣子是有解的
scipy.optimize.linprog()
你這個模型應該是沒有解的。import numpy as npimport matplotlib.pyplot as mplfrom scipy import optimizec=np.array([1,1,1])
a=np.array([[3.05,4.0,6.15]])b=np.array([7.9])res=optimize.linprog(c,-a,b)
print res.x
答案:[ 0. 0. 0.]推薦閱讀:
※通過聚類分析吃雞亞洲,北美,歐洲前百名玩家的行為
※【資料大放送】61頁PPT帶你1小時快速入門,破冰Python!
※python 括弧檢測是否匹配?
※Python安全工具開發(一) :分散式爬蟲初探