用到的是scipy.optimize中的fsolve和root这两个函数,以下是简单使用:
from scipy.optimize import root,fsolve
import numpy as np
from matplotlib import pyplot as plt
#求多元非线性方程组的解
def f1(x):
return np.array([2*x[0]**2+3*x[1]-3*x[2]**3-7,
x[0]+4*x[1]**2+8*x[2]-10,
x[0]-2*x[1]**3-2*x[2]**2+1])
sol_root = root(f1,[0,0,0])#3个0,指的的三个未知量的猜测值
sol_fsolve = fsolve(f1,[0,0,0])
print(sol_root)
print(sol_fsolve)
#求非线性方程的解
def f2(x):
return 2*np.sin(x)-x+2
x=np.linspace(-5,5,num=100)
y=f2(x)
root1=fsolve(f2,[1])#其实就是方程组等于0的根
root2=root(f2,[1])
print(root1)
print(root2)
plt.plot(x,y,'r')
plt.show()
输出如下:
fjac: array([[ 0.96686457, 0.08921948, 0.23919195],
[ 0.07663272, 0.79230209, -0.60529731],
[ 0.24351659, -0.60357045, -0.75921168]])
fun: array([-1.64249059e-10, -1.37286271e-09, 1.57796576e-09])
message: 'The solution converged.'
nfev: 26
qtf: array([-1.67013674e-09, -5.92841205e-08, -1.20357384e-08])
r: array([ 6.34170416, 2.71007612, -1.39511094, 7.99929572, 1.70538181,
-4.90041988])
status: 1
success: True
x: array([1.52964909, 0.973546 , 0.58489796])
[1.52964909 0.973546 0.58489796]
[2.75467375]
fjac: array([[-1.]])
fun: array([-1.99840144e-14])
message: 'The solution converged.'
nfev: 14
qtf: array([-1.24821238e-08])
r: array([2.85214767])
status: 1
success: True
x: array([2.75467375])
对了,还有个图: