Sympy:在有限域中求解矩阵
对于我的项目,我需要求解给定矩阵Y和K的矩阵X。(XY =
K)每个矩阵的元素必须是整数,以随机256位素数为模。解决这个问题的第一个尝试是使用SymPymod_inv(n)
函数。问题是我的矩阵大小为30的内存用完了。我的下一个想法是执行矩阵分解,因为这样可能减轻了内存的负担。但是,SymPy似乎不包含能够找到以模为模的矩阵的求解器。我可以使用任何解决方法或自制代码吗?
-
sympy
的Matrix
类支持模逆。这是模5的示例:from sympy import Matrix, pprint A = Matrix([ [5,6], [7,9] ]) #Find inverse of A modulo 26 A_inv = A.inv_mod(5) pprint(A_inv) #Prints the inverse of A modulo 5: #[3 3] #[ ] #[1 0]
该
rref
查找行还原梯形形式方法支持一个关键字iszerofunction
,指示哪些条目内的矩阵应当为零来处理。尽管我不确定,但我相信预期用途是为了保持数值稳定性(将小数设为零)。我已将其用于模块化缩减。这是模5的示例:
from sympy import Matrix, Rational, mod_inverse, pprint B = Matrix([ [2,2,3,2,2], [2,3,1,1,4], [0,0,0,1,0], [4,1,2,2,3] ]) #Find row-reduced echolon form of B modulo 5: B_rref = B.rref(iszerofunc=lambda x: x % 5==0) pprint(B_rref) # Returns row-reduced echelon form of B modulo 5, along with pivot columns: # ([1 0 7/2 0 -1], [0, 1, 3]) # [ ] # [0 1 -2 0 2 ] # [ ] # [0 0 0 1 0 ] # [ ] # [0 0 -10 0 5 ]
这是正确的,除了由返回的矩阵中
rref[0]
仍包含5和小数。通过采用mod并将分数解释为模数逆来处理此问题:def mod(x,modulus): numer, denom = x.as_numer_denom() return numer*mod_inverse(denom,modulus) % modulus pprint(B_rref[0].applyfunc(lambda x: mod(x,5))) #returns #[1 0 1 0 4] #[ ] #[0 1 3 0 2] #[ ] #[0 0 0 1 0] #[ ] #[0 0 0 0 0]