2017-04-09 125 views
2

我有非線性約束非線性函數,我想優化它。我不知道如何使用scipy.optimize定義非線性約束。我的代碼到目前爲止如下所示: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) 

回答

2

這是代碼的一些小問題;這裏是修改後的版本(下文解釋):

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]) 

的一個問題是,xy沒有在你的函數定義,我通過x[0]取代他們,分別爲x[1];也不需要使用sympy來定義您的約束條件,並且您想要返回實際的約束條件,而不是xy

+1

非常感謝! – user2702405

+1

已經完成! :) – user2702405