Easiest way to perform modular matrix inversion with Python?

前端 未结 6 1211
逝去的感伤
逝去的感伤 2020-12-25 14:32

I\'d like to take the modular inverse of a matrix like [[1,2],[3,4]] mod 7 in Python. I\'ve looked at numpy (which does matrix inversion but not modular matrix inversion) an

6条回答
  •  庸人自扰
    2020-12-25 15:21

    Okay...for those who care, I solved my own problem. It took me a while, but I think this works. It's probably not the most elegant, and should include some more error handling, but it works:

    import numpy
    import math
    from numpy import matrix
    from numpy import linalg
    
    def modMatInv(A,p):       # Finds the inverse of matrix A mod p
      n=len(A)
      A=matrix(A)
      adj=numpy.zeros(shape=(n,n))
      for i in range(0,n):
        for j in range(0,n):
          adj[i][j]=((-1)**(i+j)*int(round(linalg.det(minor(A,j,i)))))%p
      return (modInv(int(round(linalg.det(A))),p)*adj)%p
    
    def modInv(a,p):          # Finds the inverse of a mod p, if it exists
      for i in range(1,p):
        if (i*a)%p==1:
          return i
      raise ValueError(str(a)+" has no inverse mod "+str(p))
    
    def minor(A,i,j):    # Return matrix A with the ith row and jth column deleted
      A=numpy.array(A)
      minor=numpy.zeros(shape=(len(A)-1,len(A)-1))
      p=0
      for s in range(0,len(minor)):
        if p==i:
          p=p+1
        q=0
        for t in range(0,len(minor)):
          if q==j:
            q=q+1
          minor[s][t]=A[p][q]
          q=q+1
        p=p+1
      return minor
    

提交回复
热议问题