10

对于我的项目,我需要在给定矩阵 Y 和 K 的情况下求解矩阵 X。 (XY=K) 每个矩阵的元素必须是模数为随机 256 位素数的整数。我第一次尝试解决这个问题时使用了 SymPy 的mod_inv(n)函数。这样做的问题是我的内存不足,矩阵大小约为 30。我的下一个想法是执行矩阵分解,因为这可能会减少内存的负担。但是,SymPy 似乎不包含可以找到模数矩阵的求解器。我可以使用任何解决方法或自制代码吗?

4

1 回答 1

15

sympyMatrix类支持模逆。这是一个模 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]
于 2016-05-03T22:13:02.700 回答