Skip to main content
 首页 » 编程设计

python之求解具有变量约束的非线性方程组

2025年05月04日12soundcode

使用 fsolve 求解非线性方程组的一些假设示例:

from scipy.optimize import fsolve 
import math 
 
def equations(p): 
    x, y = p 
    return (x+y**2-4, math.exp(x) + x*y - 3) 
 
x, y =  fsolve(equations, (1, 1)) 
 
print(equations((x, y))) 

是否有可能使用 scipy.optimize.brentq 以某种方式解决它,例如[-1,1]?在那种情况下,解包是如何进行的?

请您参考如下方法:

正如 sascha 所建议的,约束优化是最简单的方法。 least_squares方法在这里很方便:您可以直接将您的方程式传递给它,它会最小化其分量的平方和。

from scipy.optimize import least_squares 
res = least_squares(equations, (1, 1), bounds = ((-1, -1), (2, 2))) 

bounds 的结构是((min_first_var, min_second_var), (max_first_var, max_second_var)),或者类似的更多变量。

生成的对象有一堆字段,如下所示。最相关的是: res.cost 基本上为零,这意味着找到了一个根; res.x 表示根是什么:[ 0.62034453, 1.83838393]

 active_mask: array([0, 0]) 
        cost: 1.1745369255773682e-16 
         fun: array([ -1.47918522e-08,   4.01353883e-09]) 
        grad: array([  5.00239352e-11,  -5.18964300e-08]) 
         jac: array([[ 1.        ,  3.67676787], 
       [ 3.69795254,  0.62034452]]) 
     message: '`gtol` termination condition is satisfied.' 
        nfev: 7 
        njev: 7 
  optimality: 8.3872972696740977e-09 
      status: 1 
     success: True 
           x: array([ 0.62034453,  1.83838393])