numpy.array_equal returns False for matching np arrays

84 views Asked by At

I'm having trouble getting the correct output from numpy.array_equal. The identity array is created using np.eye(size), and the result_ab array I'm comparing it with was built with np.array([]).

I keep getting the opposite result from what I expect. I've tested with both integer and float arrays and keep getting False when it should return True.

I've tested with allclose and array_equiv, but I don't think those are the right methods for this (they also tend to fail or give false positives). I've also printed the type of the result_ab and identity arrays and it returned <class 'numpy.ndarray'> for both.

I am getting an empty array for the identity output.

rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))

#create placeholder for rows and cols lists
row_list = []
col_list = []

matrix_a = []
matrix_b = []

res_ab = np.array([])

#check if matrices have same number of rows, cols
def check(rows, cols):
  if rows != cols:
    print("The matrix must be square. Enter the same number of rows and columns.")
  else:
    m_a_input(rows)
    m_b_input(rows)

#create for loop to get 1 digit per row index
def m_a_input(rows):
  for i in range(rows):
    row = list(map(int, input("Enter row digits separated by a space").split()))
    matrix_a.append(row)
  print(matrix_a)

def m_b_input(rows):
  for i in range(rows):
    row = list(map(int, input("Enter row digits separated by a space").split()))
    matrix_b.append(row)
  print(matrix_b)

def mul_matrices(matrix_a, matrix_b):
  res_ab = np.matmul(matrix_a, matrix_b)
  print(res_ab)

def is_identity(res_ab):
    # Get the size of the matrix
    size = res_ab.shape[0]
    # Create the identity matrix of the same size
    identity = np.identity(size)
    print(identity)
    print(res_ab)
    # Check if the matrix is equal to the identity matrix using numpy.allclose
    if np.array_equal(res_ab, identity) == True:
      print("true")
    else:
      print("false")

check(rows, cols)
mul_matrices(matrix_a, matrix_b)
is_identity(res_ab)```
0

There are 0 answers