Python – Cramer’s Rule for Linear Equations – With YouTube Video

Creamer’s rule for a solution of linear equations states pretty much the following:

Using this interesting picture from the German Wikipedia, I have created the following video, explaining a bit the Rule of Mr. Cramer:

Cramer's rule explanation - with Python and Excel

The video goes through the following Jupyter Notebook code:

coefficients = [
    [82, 45, 9],
    [27, 16, 3],
    [9,   5, 1]
]

results = [1, 1, 0]

def determinant_of_3x3_matrix(matrix):
    result  = (matrix[0][0] * (matrix[1][1] * matrix[2][2] - matrix[2][1]*matrix[1][2])
           ) -(matrix[0][1] * (matrix[1][0] * matrix[2][2] - matrix[1][2]*matrix[2][0])
           ) +(matrix[0][2] * (matrix[1][0] * matrix[2][1] - matrix[1][1]*matrix[2][0]))
    return result
def solve_cramer(coefficients, results):
    d = [
        [coefficients[0][0],coefficients[0][1],coefficients[0][2]],
        [coefficients[1][0],coefficients[1][1],coefficients[1][2]],
        [coefficients[2][0],coefficients[2][1],coefficients[2][2]]
    ]
    d1 = [
        [results[0], coefficients[0][1],coefficients[0][2]],
        [results[1], coefficients[1][1],coefficients[1][2]],
        [results[2], coefficients[2][1],coefficients[2][2]]
    ]
    d2 = [
        [coefficients[0][0],results[0],coefficients[0][2]],
        [coefficients[1][0],results[1],coefficients[1][2]],
        [coefficients[2][0],results[2],coefficients[2][2]]
    ]
    d3 = [
        [coefficients[0][0],coefficients[0][1],results[0]],
        [coefficients[1][0],coefficients[1][1],results[1]],
        [coefficients[2][0],coefficients[2][1],results[2]]
    ]
    
    determinant_matrix = determinant_of_3x3_matrix(d)
    determinant_d1 = determinant_of_3x3_matrix(d1)
    determinant_d2 = determinant_of_3x3_matrix(d2)    
    determinant_d3 = determinant_of_3x3_matrix(d3)
    
    print(f'determinant_matrix is {determinant_matrix}')
    print(f'determinant_d1 is {determinant_d1}')
    print(f'determinant_d2 is {determinant_d2}')
    print(f'determinant_d3 is {determinant_d3}')
    
    if determinant_matrix == 0:
        if (determinant_d1 == 0 and determinant_d2 == 0 and determinant_d3 == 0):
            return "Infinite number of solutions"
        else:
            return "No solutions"
    else:
        x = determinant_d1 / determinant_matrix
        y = determinant_d2 / determinant_matrix
        z = determinant_d3 / determinant_matrix
        
        print(f'x = {x}')
        print(f'y = {y}')
        print(f'z = {z}')
        
    return "Solution found!"

This is what you need to write, in order to run it:

solve_cramer(coefficients, results)

This is a picture of the Excel, in which I am solving the det(A), det(A1), det(A2), det(A3):

Not very fancy, but it works! 🙂