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) and I saw a few number theory packages online, but nothing that seems to do this relatively common procedure (at least, it seems relatively common to me).
By the way, the inverse of the above matrix is [[5,1],[5,3]] (mod 7). I'd like Python to do it for me though.
Python provides a very easy method to calculate the inverse of a matrix. The function numpy. linalg. inv() which is available in the python NumPy module is used to compute the inverse of a matrix.
def find_mod_inv(a,m): for x in range(1,m): if((a%m)*(x%m) % m==1): return x raise Exception('The modular inverse does not exist. ') a = 13 m = 22 try: res=find_mod_inv(a,m) print("The required modular inverse is: "+ str(res)) except: print('The modular inverse does not exist.
We use numpy. linalg. inv() function to calculate the inverse of a matrix. The inverse of a matrix is such that if it is multiplied by the original matrix, it results in identity matrix.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With