非线性优化算法求解线性规划(python)
Nlopt是一种求解非线性模型最优解的一种集合算法,尝试一下线性模型中的应用问题:x1+x2+x3<=956x1+5x2+2x3<=4005x1+2x2<=20012x1+10x2+16x3<1200x1,x2,x3>=0使得6x1+4x2+3x3最大这个其实可以用Excel或者单纯搜索法手动计算,这里测试下nlopt中的SUBPLEX算法在上面的应用import n
Nlopt是一种求解非线性模型最优解的一种集合算法,尝试一下线性模型中的应用
问题:
x1+x2+x3<=95
6x1+5x2+2x3<=400
5x1+2x2<=200
12x1+10x2+16x3<1200
x1,x2,x3>=0
使得6x1+4x2+3x3最大
这个其实可以用Excel或者单纯搜索法手动计算,这里测试下nlopt中的SUBPLEX算法在上面的应用
"""
author: Shuai-jie Shen 沈帅杰
CSDN: https://blog.csdn.net/weixin_45452300
公众号: AgBioIT
"""
import nlopt # 导入模块
# 定义代价函数
class ObjectiveFunction():
def __init__(self):
self.n_calls = 0 # 记录运行次数
# 这里代价函数的思想是不满足条件的情况下把代价函数设置成最大值,因为目前我测试的是最小化代价函数,因此返回代价函数的导数
def __call__(self, par_values, grad=None):
x1 = par_values[0]
x2 = par_values[1]
x3 = par_values[2]
obj_func = 6*x1+4*x2+3*x3
if x1+x2+x3 > 95 or 6*x1+5*x2+2*x3 > 400 or 5*x1+2*x2 > 200 or 12*x1+10*x2+16*x3 > 1200:
obj_func = 1
self.n_calls += 1
return 1/obj_func
x1 = [1,95]
x2 = [1,95]
x3 = [1,95]
objfunc_calculator = ObjectiveFunction()
opt = nlopt.opt(nlopt.LN_SBPLX, 3)
# Assign the objective function calculator
opt.set_min_objective(objfunc_calculator)
# lower bounds of parameters values
opt.set_lower_bounds([x1[0], x2[0], x3[0]])
# upper bounds of parameters values
opt.set_upper_bounds([x1[1], x2[1], x3[1]])
# the initial step size to compute numerical gradients
opt.set_initial_step([0.5,0.5,0.5])
# Maximum number of evaluations allowed
opt.set_maxeval(1000000)
# Relative tolerance for convergence
# opt.set_stopval(0.5)
opt.set_xtol_rel(1e-20)
# Start the optimization with the first guess
firstguess = [15,20,12]
x = opt.optimize(firstguess)
print("\noptimum at x1: %s, x2: %s, x3: %s,"% (x[0], x[1], x[2]))
print("function value = ", 1/(opt.last_optimum_value()))
print("result code = ", opt.last_optimize_result())
print("With %i function calls" % objfunc_calculator.n_calls)
结果
optimum at x1: 25.641044164410268, x2: 35.89738956977657, x3: 33.33334839558181,
function value = 397.43586845231334
result code = 4
With 2862 function calls
标准答案
x1: 25.6, x2: 35.9, x3: 33.3
还OK差别不大

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)