gpt4 book ai didi

python - 用 numpy 反转分数矩阵

转载 作者:行者123 更新时间:2023-12-04 17:22:49 26 4
gpt4 key购买 nike

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

[
[Fraction(1, 1), Fraction(-1, 2)],
[Fraction(-4, 9), Fraction(1, 1)]
]
我想找到它的逆。因为它有 Fraction在里面,做:
from numpy.linalg import inv
inv(M)
不起作用。我得到 TypeError: No loop matching the specified signature and casting was found for ufunc inv

最佳答案

sympy我们可以得到分数的结果。

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
带花车:
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 ⎦
使用 Rational(分数):
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 ⎦
检查 float 答案:
In [12]: M1.inv()*7
Out[12]:
⎡9.0 4.5⎤
⎢ ⎥
⎣4.0 9.0⎦
或者
In [18]: M2.inv().evalf()
Out[18]:
⎡1.28571428571429 0.642857142857143⎤
⎢ ⎥
⎣0.571428571428571 1.28571428571429 ⎦

关于python - 用 numpy 反转分数矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65164336/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com