Python SymPy 两个表达式相加
Python SymPy addition of two expressions
我在 Python SymPy
中有两个简单的表达式(M1 和 M2)。
但是,当我尝试添加这两个表达式时,出现以下错误:
"TypeError: cannot add <class 'sympy.matrices.dense.MutableDenseMatrix'> and <class 'sympy.core.mul.Mul'>"
如何添加表达式 M1 和 M2 而不会遇到此错误?
MWE:
from sympy import *
t, alpha, b1, b2, x1, x2 = symbols('t alpha beta1 beta2 X1 X2')
beta = Matrix([[b1, b2]]).T
X = Matrix([[x1, x2]]).T
M1 = t*alpha**2
M2 = X.T * (t*beta*beta.T) * X
M1 + M2 # Here I get the corresponding error
M2
的形状为 (1, 1),但它仍被视为矩阵,并且似乎不支持矩阵和标量之间的加法。来自 10 年前的 github issue:
We've already discussed scalar addition in issue 5369 and we decided not to support it, so this isn't going to happen either, unless we revert that decision.
Link 到引用的问题。
不过,你可以做到
M1 + M2[0] # this will be a scalar
或者,如果您想要矩阵形式的所有内容,即按元素添加标量
M1 * ones(M2.rows, M2.cols) + M2
我在 Python SymPy
中有两个简单的表达式(M1 和 M2)。
但是,当我尝试添加这两个表达式时,出现以下错误:
"TypeError: cannot add <class 'sympy.matrices.dense.MutableDenseMatrix'> and <class 'sympy.core.mul.Mul'>"
如何添加表达式 M1 和 M2 而不会遇到此错误?
MWE:
from sympy import *
t, alpha, b1, b2, x1, x2 = symbols('t alpha beta1 beta2 X1 X2')
beta = Matrix([[b1, b2]]).T
X = Matrix([[x1, x2]]).T
M1 = t*alpha**2
M2 = X.T * (t*beta*beta.T) * X
M1 + M2 # Here I get the corresponding error
M2
的形状为 (1, 1),但它仍被视为矩阵,并且似乎不支持矩阵和标量之间的加法。来自 10 年前的 github issue:
We've already discussed scalar addition in issue 5369 and we decided not to support it, so this isn't going to happen either, unless we revert that decision.
Link 到引用的问题。
不过,你可以做到
M1 + M2[0] # this will be a scalar
或者,如果您想要矩阵形式的所有内容,即按元素添加标量
M1 * ones(M2.rows, M2.cols) + M2