'Determinate of a Singular 4x4 matrix is non zero using numpy det

I am trying to calculate the determinate of the (4x4) matrix A using np.linalg.det([A])

Here A is defined as below

    import numpy as np
    A = np.array([
            [1, 3, 1, 2],
            [5, 8, 5, 3],
            [0, 4, 0, 0],
            [2, 3, 2, 8]
        ], dtype=np.float_)

if i run this

np.linalg.det([A])

I am getting the value as array([-4.4408921e-15]) which seems to be wrong in my sense. Because the Matrix A's 1st and 3rd column are same from my understanding of singular matrix if the columns are same i should get the det value as 0 but here i am getting a non zero value, what am i missing ?



Solution 1:[1]

It's probably because of an accuracy. Try float64.

import numpy as np

A = np.array([
        [1, 3, 1, 2],
        [5, 8, 5, 3],
        [0, 4, 0, 0],
        [2, 3, 2, 8]
    ], dtype=np.float64)

np.linalg.det([A])

Solution 2:[2]

#write a customer function to find determinate

def det_mat(m1): 
    if (len(m1)!=len(m1[0])): 
        return "Error this is not a square matrix"
     elif (len(m1) == 2):
        return (m1[0][0]*m1[1][1] - m1[0][1]*m1[1][0])
     elif (len(m1) == 3):
      # | m00 m01 m02|          
      # | m10 m11 m12 | 
      # | m20 m21 m22 |
          a=  m1[0][0]* (m1[1][1]* m1[2][2] - m1[2][1]* m1[1][2]) 
          b=  m1[0][1]* (m1[1][0]* m1[2][2] - m1[2][0]*m1[1][2]) 
          c=  m1[0][2]* (m1[1][0]* m1[2][1] - m1[2][0]*m1[1][1])                     
          return(a-b+c)     
    elif (len(m1) == 4):
     # |m00 m01 m02 m03|          
     # |m10 m11 m12 m13| 
     # |m20 m21 m22 m23|
     #| m30 m31 m32 m33|
        a1=0
        a2=0
        a3=0 
        a4=0   
        a1= m1[0][0]* (m1[1][1]* (m1[2][2]* m1[3][3] - m1[3][2]* m1[2][3]) - m1[1][2]* (m1[2][1]* m1[3][3] - m1[3][1]*m1[2][3])+  m1[1][3]* (m1[2][1]* m1[3][2] - m1[3][1]*m1[2][2]))
     print(a1)   
        a2= m1[0][1]* (m1[1][0]* (m1[2][2]* m1[3][3] - m1[3][2]* m1[2][3]) - m1[1][2]* (m1[2][0]* m1[3][3] - m1[3][0]*m1[2][3])+ m1[1][3]* (m1[2][0]* m1[3][2] - m1[3][0]*m1[2][2])) 
     #print(a2)   
        a3= m1[0][2]* (m1[1][0]* (m1[2][1]* m1[3][3] - m1[3][1]* m1[2][3]) - m1[1][1]* (m1[2][0]* m1[3][3] - m1[3][0]*m1[2][3])+  m1[1][3]* (m1[2][0]* m1[3][1] - m1[3][0]*m1[2][1])) 
      #print(a3)   
        a4= m1[0][3]* (m1[1][0]* (m1[2][1]* m1[3][2] - m1[3][1]* m1[2][2]) - m1[1][1]* (m1[2][0]* m1[3][2] - m1[3][0]*m1[2][2])+  m1[1][2]* (m1[2][0]* m1[3][1] - m1[3][0]*m1[2][1]))
     #print(a4)
     return a1-a2+a3-a4   

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Guru Prakash