Issue
Having looked over the man pages for numpy
's eye
and identity
, I'd assumed that identity
was a special case of eye
, since it has fewer options (e.g. eye
can fill shifted diagonals, identity
cannot), but could plausibly run more quickly. However, this isn't the case on either small or large arrays:
>>> np.identity(3)
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> np.eye(3)
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> timeit.timeit("import numpy; numpy.identity(3)", number = 10000)
0.05699801445007324
>>> timeit.timeit("import numpy; numpy.eye(3)", number = 10000)
0.03787708282470703
>>> timeit.timeit("import numpy", number = 10000)
0.00960087776184082
>>> timeit.timeit("import numpy; numpy.identity(1000)", number = 10000)
11.379066944122314
>>> timeit.timeit("import numpy; numpy.eye(1000)", number = 10000)
11.247124910354614
What, then, is the advantage of using identity
over eye
?
Solution
identity
just calls eye
so there is no difference in how the arrays are constructed. Here's the code for identity
:
def identity(n, dtype=None):
from numpy import eye
return eye(n, dtype=dtype)
As you say, the main difference is that with eye
the diagonal can may be offset, whereas identity
only fills the main diagonal.
Since the identity matrix is such a common construct in mathematics, it seems the main advantage of using identity
is for its name alone.
Answered By - Alex Riley
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.