You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GEKKO优化中整数变量返回小数结果的问题咨询

GEKKO优化中整数变量返回小数结果的问题咨询

大家好,我正在用GEKKO做一个切割方案优化问题——目标是在圆形区域内最大化矩形的总面积。所有变量我都预设为整数类型:

  • diam:从给定列表中选择一个整数直径
  • ep和larg:通过字典关联的整数厚度与宽度对
  • pcs:矩形的数量,范围在1到14之间,同样要求是整数

原本我用嵌套循环遍历所有可能性也能解决问题,但后续要新增变量,循环的复杂度会飙升,所以改用GEKKO,几乎所有变量都用了二进制决策变量来建模。

我的代码如下:

from gekko import GEKKO

m = GEKKO(remote=False)

#define diameter of circle
diam = [205,225,237,255,269,286,295,305]
xdiam = [m.Var(lb=0, ub=1, integer=True) for _ in diam]
m.Equation(sum(xdiam) == 1)

#define numbers of pieces
pcs = m.Var(lb=1, ub=14, integer=True, value=10)

#define thickness et width
dic = {
12:[75,95,100],
15:[95,100,150],
10:[100,135,120]}

pair = []
for cle in dic:
    for val in dic[cle]:
        xpair = m.Var(lb=0,ub=1, integer=True)
        pair.append((cle,val, xpair))
m.Equation(sum(xl[2] for xl in pair) == 1)

#constraint : diagonal of all rectangles (hypotenuse) must not exceed the diameter
pyth = m.Intermediate((((sum((e*xe) for e,_,xe in pair))*pcs +((pcs-1)*3.5))**2+(sum((l*xl) for _,l,xl in pair))**2)**0.5)
m.Equation(pyth <= sum((d*xd) for d, xd in zip(diam, xdiam)))

#Maximise area of rectangles/area of circle
rend = m.Intermediate(((sum((l*xl) for _,l,xl in pair))*(sum((e*xe) for e,_,xe in pair))*pcs)/((((sum((d*xd) for d, xd in zip(diam, xdiam)))*0.5)**2)*3.14))
m.Maximize(rend)

#Solver
m.options.SOLVER = 3
m.options.MAX_ITER = 1000
m.solve()

#Display results
for ep,larg,bin in pair:
    if float(bin.value[0]) > 0.90:
        print("thi",ep)
        print("wid",larg)
for diam, xdiam in zip(diam,xdiam):
    if xdiam.VALUE[0] > 0.9:
        print("diam",diam)
print("pcs",pcs.VALUE[0])
print("yield",rend.VALUE[0])
print("pyth",pyth.VALUE[0])

现在遇到的问题是:优化后得到的pcs(矩形数量)不是整数?这次测试里结果还接近整数,但修改字典里的参数后,甚至会出现像pcs = 5.820173这样的小数结果。

求解器的输出信息:

The solution was found.
The final value of the objective function is -0.5289469114205082

Solver : IPOPT (v3.12)
Solution time : 0.0211 sec
Objective : -0.5289469114205082
Successful solution

我的程序输出结果:

thi 15
wid 150
diam 205
pcs 7.9775445419
yield 0.52894691142
pyth 205.00005502

提前感谢大家的帮助!

备注:内容来源于stack exchange,提问作者Vincente

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 13:35:31