python - python中三对角矩阵的解决方案是什么?
问题描述
我现在正在研究一个关于三对角矩阵的问题,我在 wiki https://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm中使用了三对角矩阵算法来实现一个解决方案,我已经尝试过了,但我的解决方案并不完整。
我很困惑,我也需要帮助,这是我使用 jupyter notebook 的脚本
import numpy as np
# The diagonals and the solution vector
b = np.array((5, 6, 6, 6, 6, 6, 6, 6, 5), dtype=float) # Main Diagonal
a= np.array((1, 1, 1, 1, 1, 1, 1, 1), dtype = float) # Lower Diagonal
c = np.array((1, 1, 1, 1, 1, 1, 1, 1), dtype = float) # Upper Diagonal
d = np.array((3, 2, 1, 3, 1, 3, 1, 2, 3), dtype = float) # Solution Vector
#number of rows
n = d.size
newC = np.zeros(n, dtype= float)
newD = np.zeros(n, dtype = float)
x = np.zeros(n, dtype = float)
# the first coefficents
newC[0] = c[0] / b[0]
newD[0] = d[0] / b[0]
for i in range(1, n - 1):
newC[i] = c[i] / (b[i] - a[i] * newC[i - 1])
for i in range(1, n -1):
newD[i] = (d[i] - a[i] * newD[i - 1]) / (b[i] - a[i] * newC[i - 1])
x[n - 1] = newD[n - 1]
for i in reversed(range(0, n - 1)):
x[i] = newD[i] - newC[i] * x[i + 1]
x
解决方案
这是因为维基百科文章中的定义方式a, b, c
和d
定义。如果你仔细看,你会发现 is 的第一个元素,a
fora2
的循环也是newD
to n
。因此,为了让数组具有可理解的索引,我建议您添加一个幻像元素a1
。你得到:
import numpy as np
# The diagonals and the solution vector
b = np.array((5, 6, 6, 6, 6, 6, 6, 6, 5), dtype=float) # Main Diagonal
a = np.array((np.nan, 1, 1, 1, 1, 1, 1, 1, 1), dtype = float) # Lower Diagonal
# with added a1 element
c = np.array((1, 1, 1, 1, 1, 1, 1, 1), dtype = float) # Upper Diagonal
d = np.array((3, 2, 1, 3, 1, 3, 1, 2, 3), dtype = float) # Solution Vector
#number of rows
n = d.size
newC = np.zeros(n, dtype= float)
newD = np.zeros(n, dtype = float)
x = np.zeros(n, dtype = float)
# the first coefficents
newC[0] = c[0] / b[0]
newD[0] = d[0] / b[0]
for i in range(1, n - 1):
newC[i] = c[i] / (b[i] - a[i] * newC[i - 1])
for i in range(1, n): # Add the last iteration `n`
newD[i] = (d[i] - a[i] * newD[i - 1]) / (b[i] - a[i] * newC[i - 1])
x[n - 1] = newD[n - 1]
for i in reversed(range(0, n - 1)):
x[i] = newD[i] - newC[i] * x[i + 1]
x
推荐阅读
- c - scanf和gets有什么区别?
- websocket - 为什么我的 Socket.IO 服务器没有响应我的 Firecamp 和 C# 客户端?
- python - 如何在 Apache 服务器上托管 Dash 应用程序?
- c# - 如何使用 Powershell 在 Windows 10 上处理 LogonHours 属性?
- virtual-machine - 如何实现像 virtualbox 这样的虚拟化应用程序?
- lisp - 过滤掉除数字以外的任何值
- r - Sparklyr 无法从 Dockerfile 中的 apache 下载 Spark
- reactjs - Formik handleReset 正在通过验证
- python - FileNotFoundError:[Errno 2] 没有这样的文件或目录:'C:\\Users\\SUN\\Desktop\\oops in python.txt'
- python - 有效地为 matplotlib 中 2 x 值之间的所有点着色