matrix_3by3solve.py

Created by wperez274

Created on September 10, 2023

1.48 KB

get det & inverse of matrix


# Define a new 3x3 matrix A

A=int(input("A: "))
B=int(input("B: "))
C=int(input("C: "))

D=int(input("D: "))
E=int(input("E: "))
F=int(input("F: "))

G=int(input("G: "))
H=int(input("H: "))
I=int(input("I: "))





A = [[A, B, C],
     [D, E, F],
     [G, H, I]]

# Calculate the determinant of A manually
det_A = (A[0][0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) -
         A[0][1] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) +
         A[0][2] * (A[1][0] * A[2][1] - A[1][1] * A[2][0]))

# Check if the determinant is zero (for invertibility)
if det_A == 0:
    print("The matrix is not invertible (determinant is zero).")
else:
    # Calculate the inverse of A manually with rounding
    A_inverse = [[round((A[1][1] * A[2][2] - A[1][2] * A[2][1]) / det_A, 3),
                  round((A[0][2] * A[2][1] - A[0][1] * A[2][2]) / det_A, 3),
                  round((A[0][1] * A[1][2] - A[0][2] * A[1][1]) / det_A, 3)],
                 [round((A[1][2] * A[2][0] - A[1][0] * A[2][2]) / det_A, 3),
                  round((A[0][0] * A[2][2] - A[0][2] * A[2][0]) / det_A, 3),
                  round((A[0][2] * A[1][0] - A[0][0] * A[1][2]) / det_A, 3)],
                 [round((A[1][0] * A[2][1] - A[1][1] * A[2][0]) / det_A, 3),
                  round((A[0][1] * A[2][0] - A[0][0] * A[2][1]) / det_A, 3),
                  round((A[0][0] * A[1][1] - A[0][1] * A[1][0]) / det_A, 3)]]

    # Print the rounded inverse
    print("Inverse of A:")
    for row in A_inverse:
        print(row)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.