具有非线性约束的scipy.optimize [英] scipy.optimize with non linear constraints

查看:187
本文介绍了具有非线性约束的scipy.optimize的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有带有非线性约束的非线性函数,我想对其进行优化.我不知道如何使用scipy.optimize定义非线性约束.到目前为止,我的代码如下:

I have non-linear function with non-linear constraints and I'd like to optimize it. I don't know how to define non-linear constraints using scipy.optimize. My code so far looks like:

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)

推荐答案

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

The were a few minor issues with the code; here is the modified version (explanation below):

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.

One problem was that x and y were not defined in your functions, I replaced them by x[0] and x[1], respectively; also there was no need to use sympy to define your constraints and you want to return the actual constraint and not x and y.

这篇关于具有非线性约束的scipy.optimize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆