# 检查两个矩阵在python中是否相似

I have huge datasets consisting of numpy arrays. Suppose `A` and `B` are two square matrices of size `n`. `A` and `B` are similar if there exists a nonsingular matrix of size `n`, `S`, such that `A=S^{-1}*B*S`.

How can I determine if two matrices are similar in sympy/numpy? If the matrices are similar, how can I find the invertible matrix `S`?

• 小哥 回复

The algorithm is explained here:

There is something called "canonical forms" for a matrix; they are special forms for a matrix that can be obtained intrinsically from the matrix, and which will allow you to easily compare two matrices of the same size to see if they are similar or not. They are indeed based on eigenvalues and eigenvectors.

You can use either the Jordan canonical form (if the characteristic polynomial splits) or the rational canonical form (if the characteristic polynomial does not split) to compare the two matrices. They will be similar if and only if their rational forms are equal (up to some easily spotted differences; exactly analogous to the fact that two diagonal matrices are the same if they have the same diagonal entries, though the entries don't have to appear in the same order in both matrices).

This answer shows how to use numpy to calculate the Jordan Normal forms. If you calculate them for `A` and `B` and they are equal, then `A` and `B` are similar.