gpt4 book ai didi

python - 用python求解线性规划

转载 作者:行者123 更新时间:2023-12-05 03:28:28 25 4
gpt4 key购买 nike

我想用 Python 解决线性规划问题。模型是:

Maximizing x1 + x2  
S.t:
x1 + x2 <=1
0<= x1 , x2 <=1

所以我尝试了这个:

from gekko import GEKKO

model = GEKKO(remote=False)
x1 = model.Var(0.2 , lb=0 , ub=1)
x2 = model.Var(0.2 , lb=0 , ub=1)

model.Equation = (sum(x1 , x2) <=1)

model.Maximize(sum(x1 , x2))

但是我得到了:

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_8024/1372822120.py in <module>
6 x2 = model.Var(0.2 , lb=0 , ub=1)
7
----> 8 model.Equation = (sum(x1 , x2) <=1)
9
10 model.Maximize(sum(x1 , x2))

~\Anaconda3\envs\Python3.10\lib\site-packages\gekko\gk_variable.py in __getitem__(self, key)
78 return len(self.value)
79 def __getitem__(self,key):
---> 80 return self.value[key]
81 def __setitem__(self,key,value):
82 self.value[key] = value

~\Anaconda3\envs\Python3.10\lib\site-packages\gekko\gk_operators.py in __getitem__(self, key)
145
146 def __getitem__(self,key):
--> 147 return self.value[key]
148
149 def __setattr__(self, name, value):

TypeError: 'float' object is not subscriptable

最佳答案

正如我在评论部分提到的,只需将 sum(x1 , x2) 更改为 x1 + x2 即可解决问题。此外,您应该尝试使用 model.solve() 求解 model!所以:

from gekko import GEKKO

model = GEKKO(remote=False)
x1 = model.Var(0.2 , lb=0 , ub=1)
x2 = model.Var(0.2 , lb=0 , ub=1)

model.Equation = (x1 + x2 <=1)

model.Maximize(x1 + x2)
model.solve()

如果您想了解最优解并避免 Gekko 的完整报告,您可以设置 model.solve(disp=False) 然后尝试:

x1[0] , x2[0]

这给了我:

(1.0, 1.0)

然后你的目标函数是x1 + x2,你可以通过以下方式获得目标函数的最优值:

x1[0] + x2[0]
>>> 2.0

关于python - 用python求解线性规划,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71257238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com