数学建模--非整数规划求解的Python实现

目录

1.算法流程简介

2.算法核心代码

3.算法效果展示

1.算法流程简介

复制代码
#非线性规划模型求解:
#我们采用通用的minimize函数来求解
#minimize(f,x,method,bounds,contrains)
#f是待求函数
#x是代求的自变量
#method是求解方法
#bounds是取值范围边界
#contrains是约束条件
"""
#Question:
        min f=x1^2+x2^2+x3^2+8
        s.t.:
            x1^2-x2^2+x3^2>=0
            x1+x2^2+x3^2<=20
            -x1-x2^2+2=0
            x2+2x3^2=3
            x1,x2,x3>=0 
"""
#具体流程如下所示:
#1.设置待求函数和约束条件
#2.处理边界约束问题
#3.代入计算求解最优值

2.算法核心代码

python 复制代码
#引用库和函数
import numpy as np
from scipy.optimize import minimize
from scipy import optimize as opt

#1.设置待求函数和约束条件
def cal_fun(x):
    return x[0]*x[0]+x[1]*x[1]+x[2]*x[2]+8
def cont1(x):
    return x[0] ** 2 - x[1] + x[2] ** 2#s.t.1
def cont2(x):
    return -(x[0] + x[1] ** 2 + x[2] ** 2 - 20)#s.t.2
def cont3(x):
	return -x[0] - x[1] ** 2 + 2#s.t.3
def cont4(x):
	return x[1] + 2 * x[2] ** 2 - 3#s.t.4

#2.处理边界约束问题
b=(0,None)
rbound=(b,b,b)

con1={'type':'ineq','fun':cont1}
con2={'type':'ineq','fun':cont2}
con3={'type':'eq','fun':cont3}
con4={'type':'eq','fun':cont4}
cons=([con1,con2,con3,con4])

#3.代入计算求解最优值
x=np.array([0,0,0])
ans=minimize(cal_fun,x,method='SLSQP',bounds=rbound,constraints=cons)
x_ans=ans.x
print("最优解:"+str(cal_fun(x_ans)))
print("最优解的方案是:x1="+str(x_ans[0]),"x2="+str(x_ans[1]))

3.算法效果展示

相关推荐
IVEN_17 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang19 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮19 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling19 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮1 天前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽1 天前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健2 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞2 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers