Hi:
The program below works fine:
def matrix_inverse_mod(K, m):
"""
Returns the inverse of the matrix K mod m, if it exists.
Matrix inverse of K mod m:
- Compute `adj(K) = cof(K)^t`, the adjoint matrix of K.
- Compute `r = 1/det(K) mod m`.
- `K^(-1) = r*adj(K) mod m`.
Examples
========
>>> A = Matrix(2, 2, [1, 2, 3, 4])
>>> print matrix_inverse_mod(A, 3)
[ 8, -4]
[-6, 2]
"""
from sympy import Matrix, gcd
from sympy.ntheory import totient
phi = totient(m)
det_K = K.det()
if gcd(det_K, m) != 1:
raise ValueError('Matrix is not invertible (mod %d)'%m)
# pow(det_K, phi-1, m) raises a __sympifyit_wrapper() error, so ...
det_inv = pow(det_K, phi-1)%m
K_adj = K.cofactorMatrix().transpose()
K_inv = det_inv*K_adj
return K_inv
However, if you do the intelligent thing and use
def matrix_inverse_mod(K, m):
"""
Returns the inverse of the matrix K mod m, if it exists.
Matrix inverse of K mod m:
- Compute `adj(K) = cof(K)^t`, the adjoint matrix of K.
- Compute `r = 1/det(K) mod m`.
- `K^(-1) = r*adj(K) mod m`.
Examples
========
>>> A = Matrix(2, 2, [1, 2, 3, 4])
>>> print matrix_inverse_mod(A, 3)
[ 8, -4]
[-6, 2]
"""
from sympy import Matrix, gcd
from sympy.ntheory import totient
phi = totient(m)
det_K = K.det()
if gcd(det_K, m) != 1:
raise ValueError('Matrix is not invertible (mod %d)'%m)
det_inv = pow(det_K, phi-1, m)
K_adj = K.cofactorMatrix().transpose()
K_inv = det_inv*K_adj
return K_inv
Then you get
>>> A = Matrix(2, 2, [1, 2, 3, 4])
>>> matrix_inverse_mod(A, 5)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
...
--> 390 det_inv = pow(det_K, phi-1, m)
...
TypeError: __sympifyit_wrapper() takes exactly 2 arguments (3 given)
Does anyone know the source of this issue?
- David
--
You received this message because you are subscribed to the Google Groups
"sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sympy?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.