arn*_*obo 7 python matrix sympy matrix-factorization modular-arithmetic
对于我的项目,我需要求矩阵X给定矩阵Y和K.(XY = K)每个矩阵的元素必须是以随机256位素数为模的整数.我解决这个问题的第一次尝试使用了SymPy的mod_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]
Run Code Online (Sandbox Code Playgroud)
该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 ]
Run Code Online (Sandbox Code Playgroud)
这是正确的,除了返回的矩阵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]
Run Code Online (Sandbox Code Playgroud)