求解方程

参考:《数值分析》Timothy Sauer著,裴玉如等译,机械工业出版社 原书MatLab代码均由本人改为python

二分法

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
30
31
# 二分法
# 计算f(x)=0的近似解
# 输入区间[a,b],满足f(a)*f(b)<0,以及容差tol
# 输出近似解,xc

# 定义函数f
def f(x):
return x**3 +x-1

def bisect(a,b,tol):
if f(a)*f(b)>0:
print("输入的a和b不满足要求")
else:
fa = f(a)
fb = f(b)
while (b-a)/2>tol:
c = (b+a)/2
fc = f(c)
if fc == 0:
break
else:
if fc*fa<0:
b = c
fb = fc
else:
a = c
fa = fc
xc = (a+b)/2
return xc

print(bisect(0,1,0.0005))

不动点迭代

当对任意数\(x\)循环求解\(\cos\),最终结果会趋向于一个值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import numpy as np
import matplotlib.pyplot as plt

def cycle_solver_cos(x,times):
X = np.zeros(times)
I = np.zeros(times)
for i in range(times):
x = np.cos(x)
X[i] = x
I[i] = i
plt.plot(I,X,'o-')
plt.axhline(y=0.7390851332,c='r',ls='--')
plt.show()

cycle_solver_cos(30,28)

定义1-4: 当g(r)=r的时候,称实数r是函数g的不动点。