为什么if2/if3会产生两个不同的输出?
我在用gekko测试m.if3函数的时候,使用了if-else条件语句,但得到了两个不同的结果。下面这段代码给我的最佳结果是12。我把这个数字放到下一段代码里,用if-else语句来确保成本是匹配的,但结果却不一样。我是不是用错了if3/if2?前5天的费率是0.1,接下来的45天费率变成0.3。
尽管我在两个代码中做的事情是一样的,但输出结果却不同。
我尝试了各种方法,从使用if-else语句到使用if2语句。
1 个回答
0
其实,if2
或 if3
这个函数并不需要,因为切换的参数 duration-5
是一个固定值,并不是根据 Gekko 变量变化的。就像验证脚本一样,这两个部分可以单独计算,然后加在一起得到总费用和病人数量。
from gekko import GEKKO
m = GEKKO(remote=False)
# parameters
cost_p = 9
cost_s = 12
var1 = 50
duration = 50
x = m.Var(integer=True, lb=1)
rate1 = 0.3
rate2 = 0.1
cost1 = m.Intermediate((rate1 * cost_p * 5 + cost_s) * x)
cost2 = m.Intermediate((rate2 * cost_p * (duration-5) + cost_s) * x)
cost = m.Intermediate(cost1+cost2)
countp1 = m.Intermediate(rate1 * 5 * x)
countp2 = m.Intermediate(rate2 * (duration-5) * x)
p_count = m.Intermediate(countp1+countp2)
m.Minimize(cost)
m.Equation(p_count >= var1)
m.options.SOLVER = 1 # for MINLP solution
m.solve(disp=False)
num_sites = x.value[0]
print(f'num_s = {num_s}')
print(f'cost: {cost.value[0]}')
print(f'p_count: {p_count.value[0]}')
最优解是:
num_s = 9.0
cost: 810.0
p_count: 54.0
解决方案的验证和这个答案是一致的:
# Solution validation
# Parameters
cost_s = 9
cost_p = 12
num_p = 50
duration = 50
if duration > 5:
rate = 0.1
else:
rate = 0.3
x = 9
cost1 = (0.1 * cost_p * 45 + cost_s) * x
cost2 = (0.3 * cost_p * 5 + cost_s) * x
cost = cost1 + cost2
countp1 = 0.3 * 5 * x
countp2 = 0.1 * 45 * x
countp = countp1 + countp2
print(f'cost (validation): {cost}')
print(f'count (validation): {countp}')