Mathematical modeling__Nonlinear programming Python implementation

The scipy library is used


Linear programming means that the target models are all linear, and other than that are nonlinear programming. Use the method provided by scipy to solve this type of problem.

from scipy.optimize import minimize
import numpy as np

#定义目标函数
def fun(args):
    a,b,c,d = args
    v = lambda x: (a+x[0])/ (b+x[1]) - c*x[0] + d*x[2]
    return v

#定义约束条件
def con(args):
    # 约束条件 分为eq 和ineq
    # eq表示 函数结果等于0 ; ineq 表示 表达式大于等于0  

    x1min,x1max,x2min,x2max,x3min,x3max = args
    cons = ({
    
    'type':'ineq', 'fun': lambda x : x[0] - x1min},
            {
    
    'type':'ineq', 'fun': lambda x : -x[0] + x1max},
            {
    
    'type':'ineq', 'fun': lambda x : x[1] - x2min},
            {
    
    'type':'ineq', 'fun': lambda x : -x[1] + x2min},
            {
    
    'type':'ineq', 'fun': lambda x : x[2] - x3min},
            {
    
    'type':'ineq', 'fun': lambda x : -x[2] + x3min},

    )

    return cons

#定义常量值
args = (2,1,3,4)


#设置变量约束条件
args2 = (0.1,0.9,0.1,0.9,0.1,0.9)
cons = con(args2)


#设置初始随机值
x0 = np.asarray((0.5,0.5,0.5))
res = minimize(fun(args), x0, method='SLSQP', constraints=cons)
res

Insert image description here

Guess you like

Origin blog.csdn.net/xdg15294969271/article/details/132899096