我正试图用GEKKO Python解决一个非线性优化问题。我知道我可以将自己的函数传递给中间函数或目标函数,但由于中间函数是分段函数,所以我需要if语句。
例如:
这是我测试的结果
def calc_weighted_average(values, characteristic):
# values are the model's variables that are changed by GEKKO.
# characteristic are always the same (they are a constant list I've defined).
sum = 0
for i in range(values):
sum += values[i] * characteristic[i]
return sum / m.sum(values)
weighted_average_density = m.Intermediate(calc_weighted_average(values, density_list))
这不起作用,我不知道如何让它发挥作用
def calc_weighted_average(values, characteristic):
# values are the model's variables that are changed by GEKKO.
# characteristic are always the same (they are a constant list I've defined).
sum = 0
for i in range(values):
sum += values[i] * characteristic[i]
# Correction factor when too large
if sum > 5:
correction_factor = (sum - 5) * (0.984 ** 2)
else:
correction_factor = 0
return (sum / m.sum(values)) - correction_factor
weighted_average_density = m.Intermediate(calc_weighted_average(values, density_list))
尝试m.if3()
函数。代替:
if sum > 5:
correction_factor = (sum - 5) * (0.984 ** 2)
else:
correction_factor = 0
尝试以下代码:
correction_factor = m.if3(sum-5,0,(sum-5)*(0.984**2))
m.if2()
函数也可用作具有互补约束的数学程序(MPCC(的逻辑条件。m.if3()
函数使用二进制变量,通常性能更好,但对于大规模问题,使用许多二进制变量可能会减慢速度。