Skip to main content
 首页 » 编程设计

python之scipy.optimize 非线性约束

2024年10月01日7qlqwjy

我有非线性约束的非线性函数,我想优化它。我不知道如何使用 scipy.optimize 定义非线性约束。到目前为止,我的代码如下所示:

from math import cos, atan 
import numpy as np 
from scipy.optimize import minimize 
import sympy as sy 
 
def f(x): 
    return 0.1*x*y 
 
def ineq_constraint(x): 
    x**2 + y**2 - (5+2.2*sy.cos(10*sy.atan(x/y)))**2 
    return x,y 
 
con = {'type': 'ineq', 'fun': ineq_constraint} 
minimize(f,x0,method='SLSQP',constraints=con) 

请您参考如下方法:

代码有一些小问题;这是修改后的版本(下面的解释):

from math import cos, atan 
import numpy as np 
from scipy.optimize import minimize 
 
 
def f(x): 
    return 0.1 * x[0] * x[1] 
 
def ineq_constraint(x): 
    return x[0]**2 + x[1]**2 - (5. + 2.2 * cos(10 * atan(x[0] / x[1])))**2 
 
 
con = {'type': 'ineq', 'fun': ineq_constraint} 
x0 = [1, 1] 
res = minimize(f, x0, method='SLSQP', constraints=con) 

res 如下所示:

     fun: 0.37229877398896682 
     jac: array([ 0.16372866,  0.22738743,  0.        ]) 
 message: 'Optimization terminated successfully.' 
    nfev: 96 
     nit: 22 
    njev: 22 
  status: 0 
 success: True 
       x: array([ 2.27385837,  1.63729975]) 

一个问题是 x 和 y 没有在你的函数中定义,我用 x[0] 和 代替了它们x[1],分别;也没有必要使用 sympy 来定义你的约束,你想返回实际的约束而不是 x 和 y。