Difference between eye and Identity in SymPy

一世执手 提交于 2019-12-23 20:07:35

问题


In SymPy, what is the difference between eye(5) and Identity(5)?

If I have a matrix X, I see that X + eye(5) and X + Identity(5) give different results (the latter is not a matrix).


回答1:


SymPy distinguishes between

  • explicit matrices, which have certain size, like 3 by 3, and explicit (possibly symbolic) entries;
  • matrix expressions, which may have symbolic size, like n by n.

eye creates a matrix, Identity creates a matrix expression. For example:

n = Symbol("n")
A = Identity(n)  # works
A = eye(n)       # throws an error

One can do some computations with this object, such as

t = trace(A)     # n
B = BlockMatrix([[A, -A], [-A, A]])

When possible, a matrix expression can be turned into an explicit matrix with as_explicit method:

A = Identity(3)
print(A.as_explicit())

prints

Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])

One can use Matrix(A) to the same effect.




回答2:


Identity is more about being able to use the symbol I to stand for the identity. If you want the matrix using that, you have to do Matrix(Identity)

See:

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]])'''

Not too much is said about it in the docs.



来源:https://stackoverflow.com/questions/50854803/difference-between-eye-and-identity-in-sympy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!