我有一个决策变量向量n
,a
是一个常数向量。让我困惑的是为什么lpDot(a,n)
在约束条件下不等于lpSum([a[i] * n[i] for i in range(N)])
?
代码如下:
import pulp
import numpy as np
# params
N = 2
a = [3.5, 2]
w = [0.6, 0.4]
# lpSum
# Define the problem as a minimization problem
problem = pulp.LpProblem("lpSum", pulp.LpMinimize)
# Define decision variables
t = pulp.LpVariable.dicts('t', range(N), cat='Continuous')
n = pulp.LpVariable.dicts('n', range(N), lowBound=0, cat='Integer')
# Define the objective function
problem += pulp.lpSum(t)
# Define the constraints
problem += t[0] >= a[0] * n[0] - 6
problem += t[0] >= 6 - a[0] * n[0]
problem += t[1] >= a[1] * n[1] - 4
problem += t[1] >= 4 - a[1] * n[1]
problem += pulp.lpSum([a[i] * n[i] for i in range(N)]) <= 10
# Solve the problem
status = problem.solve()
# Convert result to numpy array
n = np.array([n[i].varValue for i in range(N)])
# Print the optimal solution
print("Optimal Solution with lpSum:")
print(n)
# lpDot
# Define the problem as a minimization problem
problem = pulp.LpProblem("lpDot", pulp.LpMinimize)
# Define decision variables
t = pulp.LpVariable.dicts('t', range(N), cat='Continuous')
n = pulp.LpVariable.dicts('n', range(N), lowBound=0, cat='Integer')
# Define the objective function
problem += pulp.lpSum(t)
# Define the constraints
problem += t[0] >= a[0] * n[0] - 6
problem += t[0] >= 6 - a[0] * n[0]
problem += t[1] >= a[1] * n[1] - 4
problem += t[1] >= 4 - a[1] * n[1]
problem += pulp.lpDot(a, n) <= 10
# Solve the problem
status = problem.solve()
# Convert result to numpy array
n = np.array([n[i].varValue for i in range(N)])
# Print the optimal solution
print("Optimal Solution with lpDot:")
print(n)
都报告"找到最优解"。对于lpSum
,它正确地生成n = [1, 2]
,而对于lpDot
,它生成n = [2, 2]
,这违反了IMO的最后一个约束。
它们是等价的,你只是把约束写错了。n
是一个字典,所以
problem += pulp.lpDot(a, n.values()) <= 10
这生产
Optimal Solution with lpDot:
[1. 2.]