我有带有非线性约束的非线性函数,我想对其进行优化。我不知道如何使用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
and y
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句