具有线性约束的Scipy非线性方程组(初学者)

2024-06-16 11:21:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我看过这个amazing example。 但我需要解有X和F边界的系统,例如:

    f1 = x+y^2 = 0
    f2 = e^x+ xy = 0
-5.5< x <0.18
2.1< y < 10.6
   # 0.15< f1 <20.5 - not useful for this example
   # -10.5< f2 < -0.16 - not useful for this example

如何将此边界约束设置为scipy的fsolve()?或者有其他方法吗? 你能给我一个简单的代码示例吗?在


Tags: 方法代码forexample系统notscipythis
2条回答

我希望这能作为你的开场白。都是there。在

import numpy as np
from scipy.optimize import minimize

def my_fun(z):
    x = z[0]
    y = z[1]

    f = np.zeros(2)
    f[0] = x + y ** 2
    f[1] = np.exp(x) + x * y
    return np.dot(f,f)

def my_cons(z):
    x = z[0]
    y = z[1]
    f = np.zeros(4)
    f[0] = x + 5.5
    f[1] = 0.18 - x
    f[2] = y - 2.1
    f[3] = 10.6 - y
    return f

cons = {'type' : 'ineq', 'fun': my_cons}
res = minimize(my_fun, (2, 0), method='SLSQP',\
           constraints=cons)
res

status: 0 success: True njev: 7 nfev: 29 fun: 14.514193585986144 x: array([-0.86901099, 2.1 ]) message: 'Optimization terminated successfully.' jac: array([ -2.47001648e-04, 3.21871972e+01, 0.00000000e+00]) nit: 7

编辑:作为对注释的回应:如果您的函数值f1f2不为零,您只需重写方程,例如:

f1=-6和f2=3

您要最小化的功能是:

^{pr2}$

这取决于系统,但在这里您可以简单地检查约束。在

首先求解非线性系统,得到一个/无/多个形式的解(x,y)。然后检查这些解决方案中哪一个(如果有的话)满足约束条件。在

相关问题 更多 >