高等数学问题的数值解(4)--解代数方程

例:求方程$x^{3}+1.1x^{2}+0.9x-1.4=0$实根的近似值,使误差不超过$10^{-6}$。要求使用三种方法:(1)二分法(2)牛顿迭代法(3)直接调用SciPy工具库

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
import numpy as np
from scipy.optimize import fsolve

def binary_search(f,eps,a,b): # 二分法函数
c = (a+b)/2
while np.abs(f(c)) > eps:
if f(a)*f(c) < 0:
b = c
else:
a = c
c = (a+b)/2
return c

def newton_iter(f,eps,x0,dx=1E-8): # 牛顿迭代法函数
def diff(f,dx=dx): # 求数值导数函数
return lambda x:(f(x+dx)-f(x-dx))/(2*dx)
df = diff(f,dx)
x1 = x0 - f(x0)/df(x0)
while np.abs(x1-x0) >= eps:
x1,x0 = x1-f(x1)/df(x1), x1
return x1

f = lambda x:x**3+1.1*x**2+0.9*x-1.4

print('二分法求得的根为:',binary_search(f,1E-6,0,1))
print('牛顿迭代法求得的根为:',newton_iter(f,1E-6,0))
print('直接调用SciPy求得的根为:',fsolve(f,0))

例:求下列非线性方程组的数值解
$
\begin{cases}
5x_{2}+3 = 0\\
4x_{1}^{2}-2sin(x_{2}x_{3}) = 0\\
x_{2}x_{3}-1.5 = 0
\end{cases}
$

1
2
3
4
5
6
from numpy import sin
from scipy.optimize import fsolve

f = lambda x:[5*x[1]+3, 4*x[0]**2-2*sin(x[1]*x[2]), x[1]*x[2]-1.5]

print('result=', fsolve(f, [1.0,1.0,1.0]))

或者写成

1
2
3
4
5
6
7
8
from numpy import sin
from scipy.optimize import fsolve

def Pfun(x):
x1,x2,x3 = x.tolist() # x转换成列表
return 5*x2+3, 4*x1**2-2*sin(x2*x3), x2*x3-1.5

print('result=', fsolve(Pfun, [1.0,1.0,1.0]))
0%