数学建模--非整数规划求解的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.算法效果展示

相关推荐
知乎的哥廷根数学学派3 小时前
基于自适应多尺度小波核编码与注意力增强的脉冲神经网络机械故障诊断(Pytorch)
人工智能·pytorch·python·深度学习·神经网络·机器学习
cnxy1884 小时前
Python爬虫进阶:反爬虫策略与Selenium自动化完整指南
爬虫·python·selenium
用户8356290780514 小时前
Python 实现 Excel 条件格式自动化
后端·python
深蓝电商API5 小时前
Scrapy管道Pipeline深度解析:多方式数据持久化
爬虫·python·scrapy
噎住佩奇5 小时前
(Win11系统)搭建Python爬虫环境
爬虫·python
basketball6165 小时前
python 的对象序列化
开发语言·python
rgeshfgreh6 小时前
Python流程控制:从条件到循环实战
前端·数据库·python
luoluoal6 小时前
基于python大数据的电影市场预测分析(源码+文档)
python·mysql·django·毕业设计·源码
幻云20106 小时前
Python深度学习:从入门到实战
人工智能·python
Zoey的笔记本7 小时前
敏捷与稳定并行:Scrum看板+BPM工具选型指南
大数据·前端·数据库·python·低代码