【问题标题】:Invert matrix of Fractions with numpy用numpy反转分数矩阵
【发布时间】:2021-03-17 17:35:21
【问题描述】:

我有一个像这样的 n*n 矩阵:

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

我想找到它的倒数。由于其中包含Fractions,因此:

from numpy.linalg import inv
inv(M)

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

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    使用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 ⎦
    

    有理数(分数):

    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 ⎦
    

    检查浮动答案:

    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 ⎦
    

    【讨论】:

      【解决方案2】:

      我在这里发现了一个类似的问题: Getting No loop matching the specified signature and casting error

      您可以使用numpy matrix 并指定dtype=float(作为建议的答案):

      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)
      

      或者您也可以使用float 数字代替Fractions

      from numpy.linalg import inv
      
      matrix = [ 
        [1/1, -1/2], 
        [-4/9, 1/1] 
      ]
      inv(matrix)
      

      【讨论】:

      • 谢谢,但这给了我浮动的答案 - 我需要分数的答案。
      • 再尝试一次。按照stackoverflow.com/a/42209716/5745962 中的建议将inv(matrix) 的值转换为Fraction 是否适合您? (即使用float数字计算inverse,然后将它们四舍五入到最接近的rational
      • 这实际上让我最终找到了答案。我就是这样做的,最后用limit_denominator() 重新转换它们。谢谢!
      • 这有点难看,因为您不一定知道为分母设置什么限制。你可以做的是乘以分母的最小公倍数,求解整数,然后再除。
      猜你喜欢
      • 1970-01-01
      • 2011-08-27
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多