SymPy 中 eye 和 Identity 的区别
Difference between eye and Identity in SymPy
在SymPy中,eye(5)
和Identity(5)
有什么区别?
如果我有一个矩阵 X
,我看到 X + eye(5)
和 X + Identity(5)
给出不同的结果(后者不是矩阵)。
Identity
更多的是可以用符号I
来代表身份。如果你想要使用它的矩阵,你必须做 Matrix(Identity)
参见:
from random import randint
from sympy import *
X = Matrix(list([randint(1, 10) for _ in range(5)] for _ in range(5)))
print(X + eye(5))
Output: Matrix([[7, 10, 5, 5, 4], [3, 7, 9, 5, 4], [1, 9, 6, 3, 4], [4, 8, 5, 2, 9], [9, 3, 6, 6, 4]])
print(X + Matrix(Identity(5)))
Same output: Matrix([[7, 10, 5, 5, 4], [3, 7, 9, 5, 4], [1, 9, 6, 3, 4], [4, 8, 5, 2, 9], [9, 3, 6, 6, 4]])
print(X + Identity(5))
'''different output more about the symbol: I + Matrix([
[6, 10, 5, 5, 4],
[3, 6, 9, 5, 4],
[1, 9, 5, 3, 4],
[4, 8, 5, 1, 9],
[9, 3, 6, 6, 3]])'''
在 docs.
中并没有过多提及
SymPy区分
- 显式矩阵,具有一定的大小,如 3 x 3 和显式(可能是符号)条目;
- 矩阵表达式,可能具有符号大小,如 n x n。
eye
创建一个矩阵,Identity
创建一个矩阵表达式。例如:
n = Symbol("n")
A = Identity(n) # works
A = eye(n) # throws an error
可以用这个对象做一些计算,比如
t = trace(A) # n
B = BlockMatrix([[A, -A], [-A, A]])
如果可能,可以使用 as_explicit
方法将矩阵表达式转换为显式矩阵:
A = Identity(3)
print(A.as_explicit())
打印
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
可以使用 Matrix(A)
达到同样的效果。
在SymPy中,eye(5)
和Identity(5)
有什么区别?
如果我有一个矩阵 X
,我看到 X + eye(5)
和 X + Identity(5)
给出不同的结果(后者不是矩阵)。
Identity
更多的是可以用符号I
来代表身份。如果你想要使用它的矩阵,你必须做 Matrix(Identity)
参见:
from random import randint
from sympy import *
X = Matrix(list([randint(1, 10) for _ in range(5)] for _ in range(5)))
print(X + eye(5))
Output: Matrix([[7, 10, 5, 5, 4], [3, 7, 9, 5, 4], [1, 9, 6, 3, 4], [4, 8, 5, 2, 9], [9, 3, 6, 6, 4]])
print(X + Matrix(Identity(5)))
Same output: Matrix([[7, 10, 5, 5, 4], [3, 7, 9, 5, 4], [1, 9, 6, 3, 4], [4, 8, 5, 2, 9], [9, 3, 6, 6, 4]])
print(X + Identity(5))
'''different output more about the symbol: I + Matrix([
[6, 10, 5, 5, 4],
[3, 6, 9, 5, 4],
[1, 9, 5, 3, 4],
[4, 8, 5, 1, 9],
[9, 3, 6, 6, 3]])'''
在 docs.
中并没有过多提及SymPy区分
- 显式矩阵,具有一定的大小,如 3 x 3 和显式(可能是符号)条目;
- 矩阵表达式,可能具有符号大小,如 n x n。
eye
创建一个矩阵,Identity
创建一个矩阵表达式。例如:
n = Symbol("n")
A = Identity(n) # works
A = eye(n) # throws an error
可以用这个对象做一些计算,比如
t = trace(A) # n
B = BlockMatrix([[A, -A], [-A, A]])
如果可能,可以使用 as_explicit
方法将矩阵表达式转换为显式矩阵:
A = Identity(3)
print(A.as_explicit())
打印
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
可以使用 Matrix(A)
达到同样的效果。