矩阵高斯消元法的反向代入函数中的错误

问题描述 投票:0回答:1

我正在尝试构建一个程序来对矩阵执行高斯消元法,我能够创建一个函数将矩阵转换为行梯形形式。但是我的后替换程序有一个错误,我尝试了很多方法但无法解决。

这是我的代码:

def back_substitution(M):
    """
    Perform back substitution on an augmented matrix (with unique solution) in reduced row echelon form to find the solution to the linear system.

    Parameters:
    - M (numpy.array): The augmented matrix in row echelon form with unitary pivots (n x n+1).

    Returns:
    numpy.array: The solution vector of the linear system.
    """
    
    # Make a copy of the input matrix to avoid modifying the original
    M = M.copy()

    # Get the number of rows (and columns) in the matrix of coefficients
    num_rows = M.shape[0]

    if num_rows == 0:
        return np.array([])
    
    # Iterate from bottom to top
    for row in reversed(range(num_rows)): 
        
        substitution_row = M[row, :-1]  # Extract the row without the last element

        # Get the index of the first non-zero element in the substitution row
        index = np.argmax(substitution_row)

        # Iterate over the rows above the substitution_row
        for j in range(row): 

            row_to_reduce = M[j, :-1]

            # Get the value of the element at the found index in the row to reduce
            value = row_to_reduce[index]
            
            # Perform the back substitution step using the formula row_to_reduce -> row_to_reduce - value * substitution_row
            row_to_reduce -= value * substitution_row

            # Replace the updated row in the matrix
            M[j, :-1] = row_to_reduce
            
    # Extract the solution from the last column
    solution = M[:, -1]
    
    return solution

错误:

Wrong output for test case check_matrix_1. 
    Expected:
     [-0.33333333 -1.33333333  2.33333333].
    Got:
 [4.         1.7        2.33333333].
Wrong output for test case check_matrix_2. 
    Expected:
     [0.7857143  1.64285714 0.        ].
    Got:
 [9.         1.64285714 0.        ].
Wrong output for test case check_matrix_3. 
    Expected:
     [19. -2.  1.].
    Got:
 [9. 6. 1.].
 1  Tests passed
 3  Tests failed

提前致谢!

我尝试以我能想到的各种方式修改

row_to_reduce
变量,但找不到解决方案。

python numpy math matrix linear-algebra
1个回答
0
投票

使用以下内容:

import numpy as np

def back_substitution(M):
  n = M.shape[0]
  solution = np.zeros(n)
  for i in reversed(range(n)):
    solution[i] =  (M[i,-1] - solution @ M[i, :-1]) / M[i,i]
  return solution
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.