numpy.array_equal对匹配数组返回False的问题求助
问题原因与修复方案
核心问题:变量作用域错误
你定义的全局变量res_ab没有被mul_matrices函数正确赋值——函数内的res_ab是局部变量,不会修改全局的空数组。当is_identity接收这个空数组时,res_ab.shape[0]返回0,创建的单位矩阵也是空的,自然和实际的矩阵乘积结果不相等。此外,np.identity默认生成浮点型数组,而你的输入矩阵是整数型,类型不匹配也会导致array_equal返回False。
修复步骤
- 修正变量作用域:让
mul_matrices返回计算结果,再赋值给全局的res_ab(更符合编程规范)。 - 统一数据类型:创建单位矩阵时指定整数类型,和输入矩阵保持一致;若涉及浮点运算,改用
np.allclose忽略微小精度误差。
修复后的完整代码
import numpy as np rows = int(input("Enter the number of rows: ")) cols = int(input("Enter the number of columns: ")) matrix_a = [] matrix_b = [] def check(rows, cols): if rows != cols: print("The matrix must be square. Enter the same number of rows and columns.") return False else: m_a_input(rows) m_b_input(rows) return True 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): return np.matmul(matrix_a, matrix_b) def is_identity(res_ab): size = res_ab.shape[0] # 创建与结果同类型的单位矩阵 identity = np.identity(size, dtype=res_ab.dtype) print("单位矩阵:") print(identity) print("乘积结果:") print(res_ab) if np.array_equal(res_ab, identity): print("true") else: # 浮点场景可选:用allclose容错精度误差 # if np.allclose(res_ab, identity): # print("true") # else: # print("false") print("false") if check(rows, cols): res_ab = mul_matrices(matrix_a, matrix_b) is_identity(res_ab)
额外说明
- 原代码中
row_list和col_list未被使用,可直接删除简化代码。 - 若矩阵运算涉及浮点数,优先使用
np.allclose,避免因浮点舍入误差导致判断错误。
内容的提问来源于stack exchange,提问作者Marshmallow
相关产品推荐
相关产品推荐

