模的乘积矩阵幂/指数?

问题描述 投票:11回答:4

是否有可能使用numpy的linalg.matrix_power取模,以使元素的大小不超过特定值?

python matrix modulo exponent
4个回答
10
投票

为了防止溢出,如果您首先对每个输入数字取模,就可以得到相同的结果;实际上:

(M**k) mod p = ([M mod p]**k) mod p,

对于矩阵 M。这来自以下两个基本身份,它们对于整数xy有效:

(x+y) mod p = ([x mod p]+[y mod p]) mod p  # All additions can be done on numbers *modulo p*
(x*y) mod p = ([x mod p]*[y mod p]) mod p  # All multiplications can be done on numbers *modulo p*

由于矩阵加法和乘法可以通过标量加法和乘法来表示,因此矩阵也具有相同的标识。这样,您只需要对较小的数字求幂(n mod p通常比n小得多),并且不太可能发生溢出。因此,在NumPy中,您只需执行

((arr % p)**k) % p

为了得到(arr**k) mod p

[如果这还不够(即,尽管[n mod p]**k很小,则n mod p可能会引起溢出),则可以将幂分解成多个幂。高于产量的基本特征

(n**[a+b]) mod p = ([{n mod p}**a mod p] * [{n mod p}**b mod p]) mod p

(n**[a*b]) mod p = ([n mod p]**a mod p)**b mod p.

因此,您可以将电源k分解为a+b+…a*b*…或其任意组合。上面的身份仅允许您对小数进行小数乘幂运算,从而大大降低了整数溢出的风险。


4
投票

使用Numpy的实现:

https://github.com/numpy/numpy/blob/master/numpy/matrixlib/defmatrix.py#L98

我通过添加一个模数项对它进行了修改。 HOWEVER,存在一个错误,即如果发生溢出,则不会引发OverflowError或任何其他类型的异常。从那时起,解决方案将是错误的。有一个错误报告here

这里是代码。小心使用:

from numpy.core.numeric import concatenate, isscalar, binary_repr, identity, asanyarray, dot
from numpy.core.numerictypes import issubdtype    
def matrix_power(M, n, mod_val):
    # Implementation shadows numpy's matrix_power, but with modulo included
    M = asanyarray(M)
    if len(M.shape) != 2 or M.shape[0] != M.shape[1]:
        raise ValueError("input  must be a square array")
    if not issubdtype(type(n), int):
        raise TypeError("exponent must be an integer")

    from numpy.linalg import inv

    if n==0:
        M = M.copy()
        M[:] = identity(M.shape[0])
        return M
    elif n<0:
        M = inv(M)
        n *= -1

    result = M % mod_val
    if n <= 3:
        for _ in range(n-1):
            result = dot(result, M) % mod_val
        return result

    # binary decompositon to reduce the number of matrix
    # multiplications for n > 3
    beta = binary_repr(n)
    Z, q, t = M, 0, len(beta)
    while beta[t-q-1] == '0':
        Z = dot(Z, Z) % mod_val
        q += 1
    result = Z
    for k in range(q+1, t):
        Z = dot(Z, Z) % mod_val
        if beta[t-k-1] == '1':
            result = dot(result, Z) % mod_val
    return result % mod_val

1
投票

显而易见的方法怎么了?

例如

import numpy as np

x = np.arange(100).reshape(10,10)
y = np.linalg.matrix_power(x, 2) % 50

0
投票

我以前的所有解决方案都存在溢出问题,因此我必须编写一种算法来解决每个整数乘法之后的溢出问题。这是我的方法:

def matrix_power_mod(x, n, modulus):
    x = np.asanyarray(x)
    if len(x.shape) != 2:
        raise ValueError("input must be a matrix")
    if x.shape[0] != x.shape[1]:
        raise ValueError("input must be a square matrix")
    if not isinstance(n, int):
        raise ValueError("power must be an integer")

    if n < 0:
        x = np.linalg.inv(x)
        n = -n
    if n == 0:
        return np.identity(x.shape[0], dtype=x.dtype)
    y = None
    while n > 1:
        if n % 2 == 1:
            y = _matrix_mul_mod_opt(x, y, modulus=modulus)
        x = _matrix_mul_mod(x, x, modulus=modulus)
        n = n // 2
    return _matrix_mul_mod_opt(x, y, modulus=modulus)


def matrix_mul_mod(a, b, modulus):
    if len(a.shape) != 2:
        raise ValueError("input a must be a matrix")
    if len(b.shape) != 2:
        raise ValueError("input b must be a matrix")
    if a.shape[1] != a.shape[0]:
        raise ValueError("input a and b must have compatible shape for multiplication")
    return _matrix_mul_mod(a, b, modulus=modulus)


def _matrix_mul_mod_opt(a, b, modulus):
    if b is None:
        return a
    return _matrix_mul_mod(a, b, modulus=modulus)


def _matrix_mul_mod(a, b, modulus):
    r = np.zeros((a.shape[0], b.shape[1]), dtype=a.dtype)
    bT = b.T
    for rowindex in range(r.shape[0]):
        x = (a[rowindex, :] * bT) % modulus
        x = np.sum(x, 1) % modulus
        r[rowindex, :] = x
    return r
© www.soinside.com 2019 - 2024. All rights reserved.