Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- try:
- import numpypy as N
- except:
- import numpy as N
- def array_equal(a1, a2):
- """
- True if two arrays have the same shape and elements, False otherwise.
- Parameters
- ----------
- a1, a2 : array_like
- Input arrays.
- Returns
- -------
- b : bool
- Returns True if the arrays are equal.
- See Also
- --------
- allclose: Returns True if two arrays are element-wise equal within a
- tolerance.
- array_equiv: Returns True if input arrays are shape consistent and all
- elements equal.
- Examples
- --------
- >>> np.array_equal([1, 2], [1, 2])
- True
- >>> np.array_equal(np.array([1, 2]), np.array([1, 2]))
- True
- >>> np.array_equal([1, 2], [1, 2, 3])
- False
- >>> np.array_equal([1, 2], [1, 4])
- False
- """
- try:
- #a1, a2 = asarray(a1), asarray(a2)
- # N.asarray(v) doesn't work - asarray is unimplemented yet, using walkaround instead.
- # TODO: may be comparison of numpy array with sparse matrix, maybe take care of it?
- # array(sparse matrix) in CPython numpy currently returns array of size one and dtype "object"
- if not isinstance(a1, N.ndarray):
- a1 = N.array(a1)
- if not isinstance(a2, N.ndarray):
- a2 = N.array(a2)
- except:
- return False
- if a1.shape != a2.shape:
- return False
- # CPython numpy version:
- #return bool(logical_and.reduce(equal(a1,a2).ravel()))
- # PyPy version:
- if a1.ndim == 0: # else bug with zero-size array indexation
- return a1 == a2
- Size = a1.size
- f1, f2 = a1.flat, a2.flat
- # TODO: replace xrange by range in Python3
- for i in xrange(Size):
- if f1.next() != f2.next(): return False
- return True
- if __name__ == '__main__':
- assert array_equal(1, 1)
- assert array_equal([1, 2], [1, 2])
- assert array_equal(N.array([1, 2]), N.array([1, 2]))
- assert array_equal([1, 2], N.array([1, 2]))
- assert not array_equal([1, 2], [1, 2, 3])
- assert array_equal(N.ones([2, 3, 4]), N.ones([2, 3, 4]))
- assert array_equal(N.ones([2, 3, 4]), N.ones([2, 3, 4], int))
- assert not array_equal(N.ones([2, 3, 4]), N.zeros([2, 3, 4], int))
- print('passed')
- #from time import time
- #n = 100000
- #m = 100
- #a = N.zeros(n)
- #b = N.ones(n)
- #t = time()
- #for i in range(m):
- # N.array_equal(a, b)
- #print('classic numpy array_equal time elapsed (on different arrays): %0.5f' % (time()-t))
- #
- #
- #t = time()
- #for i in range(m):
- # array_equal(a, b)
- #print('Alternative array_equal time elapsed (on different arrays): %0.5f' % (time()-t))
- #
- #b = N.zeros(n)
- #
- #t = time()
- #for i in range(m):
- # N.array_equal(a, b)
- #print('classic numpy array_equal time elapsed (on same arrays): %0.5f' % (time()-t))
- #
- #t = time()
- #for i in range(m):
- # array_equal(a, b)
- #print('Alternative array_equal time elapsed (on same arrays): %0.5f' % (time()-t))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement