我应该实现反向替换。我们收到行梯形矩阵A,向量b和解向量x已经被初始化。

我的代码中的索引有问题。无论我如何调整范围,我总是总是从一开始就掉线并出现超出范围的错误。我已经在纸上测试了我的解决方案,它应该做正确的事,但是,我只是无法克服索引问题。有人有任何线索吗?

def back_substitution(A: np.ndarray, b: np.ndarray) -> np.ndarray:
    n = len(b)

    if A[n-1][n-1] == 0:
        raise ValueError

    for i in range(n-1, 0, -1):
        x[i] = A[i][i]/b[i]
        for j in range (i-1, 0, -1):
            A[i][i] += A[j][i]*x[i]

    return x

x = np.zeros(1)
M = np.matrix([[1, -1, 2], [0, -1, -2], [0, 0, -6]])
c = np.matrix([[0],[0],[3]])
back_substitution(M,c)


我收到以下错误:

Traceback (most recent call last):
  File "main.py", line 167, in <module>
    back_substitution(M,c)
  File "main.py", line 125, in back_substitution
    x[i] = A[i][i]/b[i]
  File "/usr/local/lib/python3.4/dist-packages/numpy/matrixlib/defmatrix.py", line 284, in __getitem__
    out = N.ndarray.__getitem__(self, index)
IndexError: index 2 is out of bounds for axis 0 with size 1

最佳答案

您正在使用列表索引,但是数组使用两个项目的数组进行索引。而且您没有在函数内部定义x,因此它会拾取您在函数def外部定义的np.matrix并触发。因为那是一个单元素数组。

请不要再使用。

def back_substitution(A: np.ndarray, b: np.ndarray) -> np.ndarray:
    n = b.size
    x = np.zeros_like(b)

    if A[n-1, n-1] == 0:
        raise ValueError

    for i in range(n-1, 0, -1):
        x[i] = A[i, i]/b[i]
        for j in range (i-1, 0, -1):
            A[i, i] += A[j, i]*x[i]

    return x

x = np.zeros(1)
M = np.matrix([[1, -1, 2], [0, -1, -2], [0, 0, -6]])
c = np.matrix([[0],[0],[3]])
back_substitution(M,c)

关于python - python中的反向替换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47551069/

10-09 13:33