DaraJ
DaraJ

Reputation: 3076

Invert matrix of Fractions with numpy

I have an n*n matrix like so:

[
    [Fraction(1, 1), Fraction(-1, 2)],
    [Fraction(-4, 9), Fraction(1, 1)]
]

And I want to find its inverse. Since it has Fractions in it, doing:

from numpy.linalg import inv
inv(M)

Does not work. I get TypeError: No loop matching the specified signature and casting was found for ufunc inv

Upvotes: 5

Views: 2455

Answers (2)

hpaulj
hpaulj

Reputation: 231605

With sympy we can get results with fractions.

2104:~/mypy$ isympy
IPython console for SymPy 1.6.2 (Python 3.8.5-64-bit) (ground types: python)
...

In [2]: from sympy.matrices import Matrix
In [4]: from sympy import Rational

In [5]: Rational(3/4)
Out[5]: 3/4

With floats:

In [6]: M1 = Matrix([[1/1, -1/2],[-4/9, 1/1]])

In [7]: M1
Out[7]: 
⎡       1.0          -0.5⎤
⎢                        ⎥
⎣-0.444444444444444  1.0 ⎦

In [8]: M1.inv()
Out[8]: 
⎡1.28571428571429   0.642857142857143⎤
⎢                                    ⎥
⎣0.571428571428571  1.28571428571429 ⎦

With Rational (fractions):

In [9]: M2 = Matrix([[1, Rational(-1,2)],[Rational(-4,9),1]])

In [10]: M2
Out[10]: 
⎡ 1    -1/2⎤
⎢          ⎥
⎣-4/9   1  ⎦

In [11]: M2.inv()
Out[11]: 
⎡9/7  9/14⎤
⎢         ⎥
⎣4/7  9/7 ⎦

Check against the float answer:

In [12]: M1.inv()*7
Out[12]: 
⎡9.0  4.5⎤
⎢        ⎥
⎣4.0  9.0⎦

or

In [18]: M2.inv().evalf()
Out[18]: 
⎡1.28571428571429   0.642857142857143⎤
⎢                                    ⎥
⎣0.571428571428571  1.28571428571429 ⎦

Upvotes: 4

Turtlean
Turtlean

Reputation: 579

I found a similar question here: Getting No loop matching the specified signature and casting error

You could use a numpy matrix and specify dtype=float (as the suggested answer):

import numpy as np
from numpy.linalg import inv

matrix = np.matrix([ [Fraction(1, 1), Fraction(-1, 2)], [Fraction(-4, 9), Fraction(1,1)] ], dtype='float')
inv(matrix)

Or you could also use float numbers instead of Fractions

from numpy.linalg import inv

matrix = [ 
  [1/1, -1/2], 
  [-4/9, 1/1] 
]
inv(matrix)

Upvotes: 0

Related Questions