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

基于CVXPY的非线性凸极小化问题求解及代码报错修复

修正CVXPY非线性凸优化代码的TypeError问题

你遇到的TypeError源于Python原生列表不支持元素级算术运算(如d/r),且代码缺少变量定义域约束导致对数函数可能无意义。以下是修正后的代码及关键说明:

修正后的代码

import cvxpy as cp
import numpy as np

ppMax = 1

# 将所有输入列表转换为numpy数组,支持元素级运算
Tmax = np.array([1.19, 1.99, 4.16, 1.98, 2.53])
d = np.array([2648000, 5552000, 4744000, 4056000, 6168000])
p = np.array([0.19952623149688797, 0.00018021843172751523, 0.0020210434604112652, 0.001602417432034276, 0.003647501823979989])
r = np.array([8574212.020483451, 6619470.077787987, 7521159.373986546, 7135440.631765847, 6832684.423897811])
c = np.array([430000000.0, 700000000.0, 400000000.0, 220000000.0, 170000000.0])
fc = np.array([40000000000, 40000000000, 40000000000, 40000000000, 40000000000])
ff = np.array([4000000000, 4000000000, 4000000000, 4000000000, 4000000000])
W = np.array([0.7, 0.2, 0.3, 0.7, 0.5])
wt = np.array([0.609, 0.04000000000000001, 0.255, 0.308, 0.43])
we = np.array([4.336742687028045, 10.647756980938421, 8.263103073749088, 7.675258157093112, 6.322105707432189])

# 定义变量并添加非负约束,避免log(1+pp)无意义
pp = cp.Variable(5, nonneg=True)

# 修正约束条件:元素级不等式
cons = [
    cp.sum(pp) <= ppMax,
    d/r + c/fc + d/(W * cp.log(1 + pp)) <= Tmax
]

# 修正目标函数运算逻辑
objective = cp.Minimize(
    wt * (2*d/r + c/ff + c/fc + d/(W * cp.log(1 + pp))) +
    we * (2*p*(d/r) + pp * (d/(W * cp.log(1 + pp))))
)

prob = cp.Problem(objective, cons)
# 指定支持非线性凸问题的求解器
prob.solve(solver=cp.SCS)

print("最优目标值:", prob.value)
print("最优pp数组:", pp.value)

关键修正点

  1. 列表转numpy数组:所有输入数据转为numpy.array,实现元素级算术运算,解决TypeError核心问题。
  2. 变量非负约束:通过nonneg=True确保pp >= 0,避免对数函数自变量小于等于0的定义域错误。
  3. 凸性合规性:确认目标函数为凸函数(凸函数的线性组合、非负系数乘积仍为凸),约束为凸集,符合CVXPY的凸优化求解要求。
  4. 指定求解器:使用SCS求解器,适配非线性凸优化问题的求解需求。

内容的提问来源于stack exchange,提问作者Arash hosseini Rezaei

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:45:46