背景:
实现用python的optimize库的fsolve对非线性方程组进行求解。可以看到这一个问题实际上还是一个优化问题,也可以用之前拟合函数的leastsq求解。下面用这两个方法进行对比:
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
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]
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/u011702002/article/details/78078010