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

如何用scipy.optimize构建戴森球计划工厂线性规划并排查无界问题

问题分析与修正

你遇到的「无界问题」核心原因是约束条件写反了,导致线性规划模型没有限制工厂数量的上限,算法认为可以无限建造工厂,因此报错。

错误原因拆解

你的需求逻辑是:铜矿每分钟产150单位铜,每个工厂每分钟消耗60单位铜,因此总铜消耗不能超过铜矿产量,对应的数学约束应该是:
60x ≤ 150(x为工厂数量)

但你代码里的约束写的是:

A = [[-60]]
b = [150]

这等价于 -60x ≤ 150 → 60x ≥ -150,这个约束对非负的工厂数量x完全没有上限限制,x可以无限大,所以算法判断问题无界。

修正后的代码

保持目标函数的正确性(linprog默认求最小值,最大化60x等价于最小化-60x),修正约束条件:

from scipy.optimize import linprog

# 目标函数:min -60x(等价于max 60x)
c = [-60]
# 约束条件:60x ≤ 150(总铜消耗不超过铜矿产量)
A = [[60]]
b = [150]
# 工厂数量非负
copper_plate_bounds = (0, None)

res = linprog(c, A_ub=A, b_ub=b, bounds=[copper_plate_bounds], method='highs')

print(res)

输出结果与说明

运行修正后的代码,会得到如下输出:

message: Optimization terminated successfully. (HiGHS Status 7: Optimal)
     success: True
      status: 0
         fun: -150.0
           x: [2.5]
         nit: 1
       lower:  residual: [2.5]
              marginals: [0.0]
       upper:  residual: [inf]
              marginals: [0.0]
         eqlin:  residual: []
                marginals: []
       ineqlin:  residual: [0.0]
                marginals: [-1.0]
  • x: [2.5]:理论最优解是建2.5个工厂,每分钟刚好消耗150铜,产出150铜板。
  • 但游戏里工厂是整数单位,实际只能建2个(每分钟消耗120铜,产出120铜板);如果允许工厂半效率运行,2.5个的产出就是150。

整数工厂的优化方案

如果需要强制整数解,可以使用scipy.optimize.milp(混合整数线性规划),将x设为整数变量:

from scipy.optimize import milp, Bounds, LinearConstraint

c = [-60]
# 约束:60x ≤150
constraints = LinearConstraint(A=[[60]], lb=-float('inf'), ub=150)
# x为非负整数
bounds = Bounds(lb=0, ub=None, integer=True)

res = milp(c=c, constraints=constraints, bounds=bounds)
print(res)

运行后会输出x: [2],完全符合游戏内的整数工厂设定。

内容的提问来源于stack exchange,提问作者Grant Curell

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 17:45:28