我想编写一个函数,给定两个整数“ n”和“ p”,它将生成所有n阶可逆矩阵,其中元素来自{0,1,...,p-1}。我有以下代码:
import itertools
import numpy as np
def invertible_matrices(n, p):
invertibleMatrices = set()
# generates all the possible matrices
x = [y for y in range(p)]
a = [j for j in itertools.product(x, repeat=n)]
b = {k for k in itertools.product(a, repeat=n)}
for each in b:
if np.linalg.det(each) != 0:
invertibleMatrices.add(each)
return invertibleMatrices
对于n=2
和p=2
,它工作正常,但对于n=2
和p=3
,我得到50
,而答案是48
。任何帮助将不胜感激。
p.s:如果您熟悉群论,我正在尝试查找GL(n, p)的所有元素(具有p个元素的有限域上的一般线性组)
我想您想要行列式模p。
if not np.isclose((np.linalg.det(each)+1)%p,1):
invertibleMatrices.add(each)
注意:+1是为了避免出现小的数字错误。
使用设定的理解:
import itertools
import numpy as np
def invertible_matrices(n, p):
"""Generates all the possible matrices."""
x = [y for y in range(p)]
a = [j for j in itertools.product(x, repeat=n)]
invertible_matrices = {k
for k in itertools.product(a, repeat=n)
if not np.isclose((np.linalg.det(k) + 1) % p, 1)
}
return len(invertible_matrices)
print(invertible_matrices(n=2, p=2))
print(invertible_matrices(n=2, p=3))
返回:
6
48