计算4x4辅助因子矩阵时出错

作为一个周末项目的一部分,我开始用python制作数字矩阵处理器。到目前为止,我已经成功实现了矩阵的加法,乘法,转置和行列式。

当我对实现进行编码时,以此来找到给定矩阵的逆(A ^ -1 = C ^ T / det(A))

其中C ^ T是由矩阵AA的所有元素的辅因子组成的矩阵,该元素沿主对角线转置。

我的程序正确计算了3x3和许多4x4的逆(通过测试集进行了测试)。但是,它在给定矩阵为

2.65 3.54 3.88 8.99
3.12 5.45 7.77 5.56
5.31 2.23 2.33 9.81
1.67 1.67 1.01 9.99

下面是我的代码来计算这个和产生的错误。

class Matrix(object):
    def __init__(self, R=1, C=1):
        """
        takes two ints : R and C specifying rows and columns of matrix
        Default is 1x1 0 matrix (or simply 0).
        """
        self.R = int(R)
        self.C = int(C)
        self.matrix = [[0 for c in range(self.C)] for r in range(self.R)]

    def check_dims(self, other):
        if (self.R == other.R) and (self.C == other.C):
            return True
        else:
            return False

    def has_floats(self, inp):
        return ((sum([elem.isdigit() for elem in inp])) < len(inp))

    def make(self):
        for i in range(self.R):
            row = input().split(maxsplit=self.C)
            if self.has_floats(row):
                self.matrix[i] = list(map(float, row))
            else:
                self.matrix[i] = list(map(int, row))

    def __str__(self):
        vis = ""
        for i in range(self.R):
            vis += f'{" ".join([str(j) for j in self.matrix[i]])}\n'
        return vis

    def __mul__(self, other):
        # Case 1: Integer multiplication
        if isinstance(other, int) or isinstance(other, float):
            M = Matrix(self.R, self.C)
            M.matrix = [[round(n * other, 3) for n in self.matrix[i]] for i in range(self.R)]
        # Case 2: Matrix multiplication
        elif isinstance(other, Matrix):
            if self.C != other.R: raise ValueError
            M = Matrix(self.R, other.C)
            for i in range(self.R):
                for j in range(other.C):
                    for k in range(other.R):
                        M.matrix[i][j] += self.matrix[i][k] * other.matrix[k][j]
        else:
            return "The operation cannot be performed."
        return M

    def transpose(self, m):
        M = Matrix(self.R, self.C)
        M.matrix = [[m[j][i] for j in range(self.C)] for i in range(self.R)]
        return M

    def cofactor_matrix(self, A):
        clis = []
        # Base Case
        if len(A) == 2 and len(A[0]) == 2:
            v = A[0][0] * A[1][1] - A[1][0] * A[0][1]
            return v
        for i in range(len(A)):
            cl = []
            for j in range(len(A)):
                B = A.copy()
                del B[i]
                for k in range(len(B)):
                    B[k] = B[k][0:j] + B[k][j + 1:]
                s = (-1) ** ((i+j)%2)
                C = self.cofactor_matrix(B)
                cl.append(s * C)
            clis.append(cl)
        return clis

    def inverse(self):
        M = self.matrix
        if (self.det_recur(M) != 0) and (self.R == self.C):
            cf_mat  = self.cofactor_matrix(M)
            cf_mat_T = self.transpose(cf_mat)
            t = 1 / self.determinant()
            return (cf_mat_T)
        else:
            return "This matrix doesn't have an inverse."

# Omitted functions for determinant since they were working corretly

这样称呼:

a, b = map(int, input("Enter matrix size: ").split())
A = Matrix(a, b)
print("Enter matrix: ")
A.make()
print("The result is: ")
print(A.inverse())

找到逆时产生的错误是:

  File "/home/pseudocodenerd/Documents/son_of_bruh/Untitled-2.py", line 229, in init
    print(A.inverse())
  File "/home/pseudocodenerd/Documents/son_of_bruh/Untitled-2.py", line 141, in inverse
    return (cf_mat_T * t)
  File "/home/pseudocodenerd/Documents/son_of_bruh/Untitled-2.py", line 58, in __mul__
    M.matrix = [[round(n * other, 3) for n in self.matrix[i]] for i in range(self.R)]
  File "/home/pseudocodenerd/Documents/son_of_bruh/Untitled-2.py", line 58, in <listcomp>
    M.matrix = [[round(n * other, 3) for n in self.matrix[i]] for i in range(self.R)]
  File "/home/pseudocodenerd/Documents/son_of_bruh/Untitled-2.py", line 58, in <listcomp>
    M.matrix = [[round(n * other, 3) for n in self.matrix[i]] for i in range(self.R)]
TypeError: can't multiply sequence by non-int of type 'float'

我已经从可靠的Ti计算器中检查到,我的程序可以正确计算行列式。

There is a bug in the cofactor_matrix() function which I cannot find.

产生的辅因子矩阵(恰好在将其乘以1 /行列式之前给出)。

[[13.3686, -5.895, -1.6387999999999998], [-72.0067, 45.16030000000001, 7.471399999999999], [63.268899999999995, -41.0657, -4.628599999999997]] [] [[72.0067, -45.16030000000001, -7.471399999999999], [-29.6813, 20.351300000000002, 2.9041999999999994], [-48.2795, 29.313100000000002, 6.359799999999996]] []
[] [[13.3686, -36.664199999999994, 1.4719999999999995], [-29.6813, 11.460200000000002, 3.8030999999999997], [17.116100000000003, 21.740399999999998, -14.428299999999998]] [] [[63.268899999999995, -1.0836000000000077, -33.98909999999999], [-17.116100000000003, -21.740399999999998, 14.428299999999998], [-48.2795, 13.314800000000002, 8.484899999999998]]
[[5.895, -36.664199999999994, 5.143599999999999], [-45.16030000000001, 21.8836, 3.8911], [41.0657, -1.0836000000000077, -21.9819]] [] [[45.16030000000001, -21.8836, -3.8911], [-20.351300000000002, 11.460200000000002, 1.4863], [-29.313100000000002, 13.314800000000002, 3.3977000000000004]] []
[] [[-1.6387999999999998, -1.4719999999999995, 5.143599999999999], [2.9041999999999994, -3.8030999999999997, 1.4863], [-0.40419999999999945, 14.428299999999998, -12.8879]] [] [[-4.628599999999997, 33.98909999999999, -21.9819], [0.40419999999999945, -14.428299999999998, 12.8879], [6.359799999999996, -8.484899999999998, 3.3977000000000004]]

This doesn't look correct. Please find any errors in my cofactor_matrix(self, A): function.

谢谢。

评论