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

相关推荐
bitbrowser38 分钟前
哪些指纹浏览器支持模拟SSL指纹
网络·python·网络协议·ssl
limenga1022 小时前
TensorFlow Keras:快速搭建神经网络模型
人工智能·python·深度学习·神经网络·机器学习·tensorflow
心软小念2 小时前
用Python requests库玩转接口自动化测试!测试工程师的实战秘籍
java·开发语言·python
sanggou3 小时前
【Python爬虫】手把手教你从零开始写爬虫,小白也能轻松学会!(附完整源码)
开发语言·爬虫·python
geng_zhaoying4 小时前
在VPython中使用向量计算3D物体移动
python·3d·vpython
半tour费4 小时前
TextCNN-NPU移植与性能优化实战
python·深度学习·分类·cnn·华为云
普通网友5 小时前
使用Flask快速搭建轻量级Web应用
jvm·数据库·python
百锦再5 小时前
第17章 模式与匹配
开发语言·后端·python·rust·django·内存·抽象
普通网友5 小时前
Python函数定义与调用:编写可重用代码的基石
jvm·数据库·python
普通网友5 小时前
使用Python进行PDF文件的处理与操作
jvm·数据库·python