用 numpy 求逆分数矩阵

Dar*_*ava 5 python numpy

我有一个 n*n 矩阵,如下所示:

[
    [Fraction(1, 1), Fraction(-1, 2)],
    [Fraction(-4, 9), Fraction(1, 1)]
]
Run Code Online (Sandbox Code Playgroud)

我想找到它的倒数。Fraction由于其中有s,因此执行以下操作:

from numpy.linalg import inv
inv(M)
Run Code Online (Sandbox Code Playgroud)

不起作用。我明白了TypeError: No loop matching the specified signature and casting was found for ufunc inv

hpa*_*ulj 3

有了sympy分数我们就可以得到结果。

\n
2104:~/mypy$ isympy\nIPython console for SymPy 1.6.2 (Python 3.8.5-64-bit) (ground types: python)\n...\n\nIn [2]: from sympy.matrices import Matrix\nIn [4]: from sympy import Rational\n\nIn [5]: Rational(3/4)\nOut[5]: 3/4\n
Run Code Online (Sandbox Code Playgroud)\n

带浮标:

\n
In [6]: M1 = Matrix([[1/1, -1/2],[-4/9, 1/1]])\n\nIn [7]: M1\nOut[7]: \n\xe2\x8e\xa1       1.0          -0.5\xe2\x8e\xa4\n\xe2\x8e\xa2                        \xe2\x8e\xa5\n\xe2\x8e\xa3-0.444444444444444  1.0 \xe2\x8e\xa6\n\nIn [8]: M1.inv()\nOut[8]: \n\xe2\x8e\xa11.28571428571429   0.642857142857143\xe2\x8e\xa4\n\xe2\x8e\xa2                                    \xe2\x8e\xa5\n\xe2\x8e\xa30.571428571428571  1.28571428571429 \xe2\x8e\xa6\n
Run Code Online (Sandbox Code Playgroud)\n

有理数(分数):

\n
In [9]: M2 = Matrix([[1, Rational(-1,2)],[Rational(-4,9),1]])\n\nIn [10]: M2\nOut[10]: \n\xe2\x8e\xa1 1    -1/2\xe2\x8e\xa4\n\xe2\x8e\xa2          \xe2\x8e\xa5\n\xe2\x8e\xa3-4/9   1  \xe2\x8e\xa6\n\nIn [11]: M2.inv()\nOut[11]: \n\xe2\x8e\xa19/7  9/14\xe2\x8e\xa4\n\xe2\x8e\xa2         \xe2\x8e\xa5\n\xe2\x8e\xa34/7  9/7 \xe2\x8e\xa6\n
Run Code Online (Sandbox Code Playgroud)\n

检查浮动答案:

\n
In [12]: M1.inv()*7\nOut[12]: \n\xe2\x8e\xa19.0  4.5\xe2\x8e\xa4\n\xe2\x8e\xa2        \xe2\x8e\xa5\n\xe2\x8e\xa34.0  9.0\xe2\x8e\xa6\n
Run Code Online (Sandbox Code Playgroud)\n

或者

\n
In [18]: M2.inv().evalf()\nOut[18]: \n\xe2\x8e\xa11.28571428571429   0.642857142857143\xe2\x8e\xa4\n\xe2\x8e\xa2                                    \xe2\x8e\xa5\n\xe2\x8e\xa30.571428571428571  1.28571428571429 \xe2\x8e\xa6\n
Run Code Online (Sandbox Code Playgroud)\n