【问题标题】:Sum of a list of SymPy matricesSymPy 矩阵列表的总和
【发布时间】:2018-03-15 05:27:33
【问题描述】:

我的 python 列表包含 sympy 矩阵对象,我需要将它们全部相加。 如果所有列表元素都只是符号,那么在 python 中使用内置的 sum 函数就可以了。

import sympy as sp
x = sp.symbols('x')
ls = [x, x+1, x**2]
print(sum(ls))

>>> x**2 + 2*x + 1

但是对于矩阵类型的元素,sum函数看起来不起作用。

import sympy as sp
ls = [sp.eye(2), sp.eye(2)*5, sp.eye(2)*3]
print(sum(ls))

>>> TypeError: cannot add <class 'sympy.matrices.dense.MutableDenseMatrix'> and <class 'int'>

我该如何解决这个问题?

【问题讨论】:

    标签: python sympy


    【解决方案1】:

    这就是为什么 Python 的 sum function 有一个可选的“开始”参数:所以你可以用你正在添加的那种“零对象”来初始化它。在这种情况下,使用零矩阵。

    >>> print(sum(ls, sp.zeros(2)))
    Matrix([[9, 0], [0, 9]])
    

    【讨论】:

      【解决方案2】:

      我真的不知道内置函数sum 是如何工作的,也许它有点像这样。

      def _sum(data):
          total = 0
          for i in data:
              total += i
          return total
      

      现在考虑以下代码行。

      >>> import sympy
      >>> x = sympy.symbols('x')
      >>> x
      x
      >>> print(0+x)
      x
      >>> x = sympy.symbols('x')
      >>> matrix=sympy.eye(3)
      >>> matrix
      Matrix([
      [1, 0, 0],
      [0, 1, 0],
      [0, 0, 1]])
      >>> print(0+x)
      x
      >>> print(0+matrix)
      Traceback (most recent call last):
        File "<pyshell#50>", line 1, in <module>
          print(0+matrix)
        File "C:\Python36\lib\site-packages\sympy\core\decorators.py", line 132, in binary_op_wrapper
          return func(self, other)
        File "C:\Python36\lib\site-packages\sympy\matrices\common.py", line 2061, in __radd__
          return self + other
        File "C:\Python36\lib\site-packages\sympy\core\decorators.py", line 132, in binary_op_wrapper
          return func(self, other)
        File "C:\Python36\lib\site-packages\sympy\matrices\common.py", line 1964, in __add__
          raise TypeError('cannot add %s and %s' % (type(self), type(other)))
      TypeError: cannot add <class 'sympy.matrices.dense.MutableDenseMatrix'> and <class 'int'>
      >>> 
      

      我们可以得出的结论是,您将任何 sympy.core.symbol.Symbol(顺便说一下,还有 Sum 和 Pow 之类的更多)添加到整数而不是 sympy.matrices.dense.MutableDenseMatrix

      【讨论】:

      • sum 函数的start 参数的作用看起来像是决定了返回类型和起始值以及要添加的类型。最初它被设置为一个整数零,所以正常的求和是有效的,但是由于我添加的是 Sympy.Matrix 类型,所以起始值也应该是那个类型。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      • 2019-09-16
      • 1970-01-01
      相关资源
      最近更新 更多