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

使用CVXPY时如何在指数项中使用决策变量

问题解决方法

报错原因

  • 你使用了Python标准库math模块的exp函数处理CVXPY决策变量,math.exp仅支持实数值输入,无法识别CVXPY的Variable类型对象,因此抛出TypeError: must be real number, not index报错。
  • CVXPY要求所有作用于决策变量的运算都必须使用其内置的符合DCP( disciplined convex programming )规则的原子函数,不能直接用Python原生数值运算库的函数。

解决步骤

将目标函数中的math.exp替换为CVXPY内置的cp.exp即可,修改后的完整代码如下:

import cvxpy as cp
import numpy as np

A = np.array([0.805156521,0.464522,0.00452762,0.00047562])
Zmax = 200
Zmin = 25
T = cp.Variable(2)

# 替换math.exp为cp.exp
objective = cp.Minimize((A[0]+A[1])*cp.exp(T[0]) + (A[2]+A[3])*cp.exp(T[1]))

constraints = []
constraints += [cp.sum(T) == 250]
constraints += [Zmin <= T]
constraints += [T <= Zmax]

prob = cp.Problem(objective, constraints)
prob.solve()

# 输出结果
print("\nThe optimal value is", prob.value)
print("A solution T is")
print(T.value)

运行说明

修改后使用CVXPY默认求解器即可正常求解,该目标函数是凸函数,约束为线性约束,属于凸优化问题,存在全局最优解。

内容的提问来源于stack exchange,提问作者Ajinkya Bankar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:15:00