Solving a matrix with Crammers Rule in python

Question:

I’m trying to make a function where I can give it a matrix and the constants and solving it using crammers rule. This will soon be used with complex numbers.

import numpy as np
import sympy as smp

def crammer(matrix, constants):
     D = np.linalg.det(matrix)
     dets = []
     dets.append(D)
     for i in range(0, len(constants[0]), 1):
          Dv = matrix
          Dv[:, i:i+1] = constants.T
          print(Dv)
          Dd = np.linalg.det(Dv)

          dets.append(Dd)
return dets


Mat = np.array([[2, 1,-1],
                [3, 2, 2],
                [4,-2, 3]])

Con = np.array([[1,13,9]])

print(crammer(Mat, Con))

I get this as the result:

[33.000000000000014, 33.000000000000014, 0.0, 0.0]

The first two are right the Determinate is D:33 and Dx:33 but Dy and Dz should be Dy:66 and Dz: 99.

following Crammers Rule it should be:

[[ 1  1 -1]
 [13  2  2]
 [ 9 -2  3]]
[[ 2  1 -1]
 [ 3 13  2]
 [ 4  9  3]]
[[ 2  2  1]
 [ 3  2 13]
 [ 4 -2  9]]

when I print Dv at the beginning of the for loop I get the following:

[[ 1  1 -1]
 [13  2  2]
 [ 9 -2  3]]
[[ 1  1 -1]
 [13 13  2]
 [ 9  9  3]]
[[ 1  1  1]
 [13 13 13]
 [ 9  9  9]]

I tried printing the matrix at the top of the for loop as well and I get the same problem. As I can tell my for loop is is changing my original matrix and I don’t understand why.

Asked By: Zachariah Loewen

||

Answers:

Unsure what the algorithm itself is trying to accomplish, but from a Python perspective, by assigning Dv = matrix, you’re creating a shallow copy by reference that then gets modified by the rest of the code in the loop.

I replaced this assignment with Dv = deepcopy(matrix) (use from copy import deepcopy) to create a deep copy, fresh from the original matrix.

That produced this result, which seems in line with what you predicted:

[33.000000000000014, 33.000000000000014, 66.00000000000003, 99.00000000000007]

copy documentation

Answered By: t_krill
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.