cvxpy中的剩余操作

问题描述

是否有任何内置函数来计算 cvxpy 中变量的余数?例如,以下示例代码

m = 3
n = 2
k = 5
A = cp.Variable((m,n),boolean=True)
B = np.ones((1,m))
C = np.ones(n)
constraints = []
objective = cp.Maximize((B@A%2)@C)
prob = cp.Problem(objective,constraints)
optimal_value = prob.solve()

给出错误

Exception has occurred: TypeError
unsupported operand type(s) for %: 'MulExpression' and 'int'

因为%操作

解决方法

余数 r = a mod n,带 a ≥ 0,可以找到:

  a = q*n + r      (assume n is constant) 
  q ∈ {0,1,...}    (integer variable,non-negative}
  r ∈ {0,..,n-1}   (integer variable between 0 and n-1)

这只是一个线性约束。另见:https://en.wikipedia.org/wiki/Modulo_operation