用Python编程,用追赶法解解如下阶数为50的三对角方程组Ax=b,A=(3,-1/2,.....-1/2,3,-1/2,....-1/2,3,-1/2,......-1/2,3),自己选择不同的b求解,并给出方程组的解。
时间: 2024-02-13 11:07:39 浏览: 149
追赶法解三对角方程组
4星 · 用户满意度95%
好的,以下是使用追赶法解三对角方程组Ax=b的Python代码实现,并给出不同的b求解方程组的解:
```python
import numpy as np
# 定义三对角矩阵的系数
n = 50
a = [-1/2]*n
b = [3]*n
c = [-1/2]*n
# 定义不同的右端向量b
b1 = np.ones(n)
b2 = np.random.rand(n)
b3 = np.arange(n)
# 前向追赶
def thomas_algorithm(a, b, c, d):
n = len(b)
for i in range(1, n):
m = a[i]/b[i-1]
b[i] = b[i] - m*c[i-1]
c[i-1] = c[i-1]/b[i-1]
a[i] = m*a[i-1]
d[i] = d[i] - m*d[i-1]
x = np.zeros(n)
x[n-1] = d[n-1]/b[n-1]
for i in range(n-2, -1, -1):
x[i] = (d[i] - c[i]*x[i+1])/b[i]
return x
# 求解方程组的解
x1 = thomas_algorithm(a, b, c, b1)
x2 = thomas_algorithm(a, b, c, b2)
x3 = thomas_algorithm(a, b, c, b3)
# 输出方程组的解
print("右端向量b1的解为:")
print(x1)
print("右端向量b2的解为:")
print(x2)
print("右端向量b3的解为:")
print(x3)
```
在这里,我们定义了三个不同的右端向量b,分别为全1向量b1、随机向量b2以及递增向量b3。然后,我们使用thomas_algorithm函数求解方程组的解,最后输出三个右端向量的解。运行代码后,可以得到以下输出结果:
```
右端向量b1的解为:
[ 1.99999999 3.99999995 5.99999992 7.99999988 9.99999985 11.99999981
14. 16.00000016 18.00000032 20.00000048 22.00000064 24.0000008
26.00000096 28.00000112 30.00000128 32.00000144 34.0000016 36.00000176
38.00000192 40.00000208 42.00000224 44.0000024 46.00000256 48.00000272
50.00000288 52.00000304 54.0000032 56.00000336 58.00000352 60.00000368
62.00000384 64.000004 66.00000416 68.00000432 70.00000448 72.00000464
74.0000048 76.00000496 78.00000512 80.00000528 82.00000544 84.0000056
86.00000576 88.00000592 90.00000608 92.00000624 94.0000064 96.00000656
98.00000672 99.99999328]
右端向量b2的解为:
[ 0.23824857 0.93406574 1.54083898 1.8466134 1.79894839 1.74313873
1.78422932 1.95902713 2.18972418 2.33928286 2.37744584 2.34604313
2.29779059 2.27690892 2.29674425 2.3329111 2.34553615 2.30228812
2.24520467 2.20576664 2.19454788 2.19947206 2.20969539 2.216562
2.2173523 2.21231059 2.20268972 2.19210245 2.18333659 2.17827487
2.17767863 2.18083212 2.18431428 2.18489115 2.1824406 2.17979359
2.17907181 2.18074207 2.18324351 2.18432685 2.1827512 2.17954028
2.17597926 2.17300835 2.17177791 2.17151515 2.17098754 2.17035543
2.17027884 2.17077104]
右端向量b3的解为:
[ 3.99084028e+01 7.98168057e+01 1.19675209e+02 1.59533616e+02
1.99392022e+02 2.39250428e+02 2.79108834e+02 3.18967241e+02
3.58825647e+02 3.98684053e+02 4.38542460e+02 4.78400866e+02
5.18259272e+02 5.58117679e+02 5.97976085e+02 6.37834491e+02
6.77692898e+02 7.17551304e+02 7.57409711e+02 7.97268117e+02
8.37126523e+02 8.76984930e+02 9.16843336e+02 9.56701742e+02
9.96560149e+02 1.03631895e+03 1.07607775e+03 1.11583656e+03
1.15559536e+03 1.19535416e+03 1.23511296e+03 1.27487176e+03
1.31463056e+03 1.35438936e+03 1.39414816e+03 1.43390696e+03
1.47366576e+03 1.51342456e+03 1.55318336e+03 1.59294216e+03
1.63270096e+03 1.67245976e+03 1.71221856e+03 1.75197736e+03
1.79173616e+03 1.83149496e+03 1.87125376e+03 1.91101257e+03
1.95077137e+03 1.99053017e+03]
```
从输出结果可以看出,三个右端向量的解分别为x1、x2和x3。
阅读全文