Untitled

mail@pastecode.io avatar
unknown
python
a month ago
1.5 kB
2
Indexable
Never
from matrixOperations import *
from q1e import *

#def matrix_minor(matrix, row, col):
#    return [row[:col] + row[col+1:] for row in (matrix[:row]+matrix[row+1:])]

#def matrix_determinant(matrix):
#    if len(matrix) == 2:
#        return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0]
#    determinant = 0
#    for c in range(len(matrix)):
#        determinant += ((-1)**c)*matrix[0][c]*matrix_determinant(matrix_minor(matrix, 0, c))
#    return determinant

def matrix_inverse(matrix):
    determinant = det(matrix)
    if determinant == 0:
        raise ValueError("A matriz não é invertível.")
    if len(matrix) == 2:
        return [[matrix[1][1]/determinant, -1*matrix[0][1]/determinant],
                [-1*matrix[1][0]/determinant, matrix[0][0]/determinant]]
    cofactors = []
    for r in range(len(matrix)):
        cofactor_row = []
        for c in range(len(matrix)):
            matrix_minor = minor(matrix, r, c)
            cofactor_row.append(((-1)**(r+c)) * det(matrix_minor))
        cofactors.append(cofactor_row)
    cofactors = transpose(cofactors)
    for r in range(len(cofactors)):
        for c in range(len(cofactors)):
            cofactors[r][c] = cofactors[r][c]/determinant
    return cofactors

# Exemplo de uso:
matrix = [[4, 7, 9],
          [5, 2, 3],
          [1, 6, 8]]
vector = [1,2,3]
print("Número condição:", frobenius(matrix_inverse(matrix)) * frobenius(matrix))
print("Estimativa:", frobenius(matrix) * frobenius(matrix_inverse(mult(matrix, vector))) / frobenius(vector))
Leave a Comment