Scipy - Non-linear Equations System with linear constraints (beginner)

别等时光非礼了梦想. 提交于 2019-12-10 12:02:11

问题


I have seen this amazing example. But I need to solve system with boundaries on X and F, for example:

    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

How could I set this boundary constrains to fsolve() of scipy? Or may be there is some other method? Would You give me a Simple code example?


回答1:


It depends on the system, but here you can simply check the constraints afterwards.

First solve your nonlinear system to get one/none/several solutions of the form (x,y). Then check which, if any, of these solutions, satisfy the constraints.




回答2:


I hope this will serve you as a starter. It was all 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

EDIT: As a response to the comments: If your function values f1 and f2 are not zero you just have to rewrite the equations e.g:

f1 = -6 and f2 = 3

Your function to minimize will be:

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

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


来源:https://stackoverflow.com/questions/30378861/scipy-non-linear-equations-system-with-linear-constraints-beginner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!