python用fsolve、leastsq对非线性方程组进行求解

背景:

实现用python的optimize库的fsolve对非线性方程组进行求解。可以看到这一个问题实际上还是一个优化问题,也可以用之前拟合函数的leastsq求解。下面用这两个方法进行对比:

代码:

from scipy.optimize import fsolve,leastsq
from math import sin,cos

def f(x):
    x0 = float(x[0])
    x1 = float(x[1])
    x2 = float(x[2])
    return [
        5*x1+3,
        4*x0*x0 - 2*sin(x1*x2),
        x1*x2-1.5
        ]

x0 = [1,1,1]
result = fsolve(f,x0)

print("===================")
print()
print("求解函数名称:",fsolve.__name__)
print("解:",result)
print("各向量值:",f(result))
#拟合函数来求解
h = leastsq(f,x0)

print("===================")
print()
print("求解函数名称:",leastsq.__name__)
print("解:",h[0])
print("各向量的值:",f(h[0]))

结果:

===================


求解函数名称: fsolve
解: [-0.70622057 -0.6        -2.5       ]
各向量值: [0.0, -9.126033262418787e-14, 5.329070518200751e-15]
===================


求解函数名称: leastsq
解: [-0.70622057 -0.6        -2.5       ]
各向量的值: [0.0, -2.220446049250313e-16, 0.0]

你可能感兴趣的:(python_numpy)