pyxx.arrays.is_array_equal#
- pyxx.arrays.is_array_equal(item1: Array_or_Number_or_String, item2: Array_or_Number_or_String, *args: Array_or_Number_or_String, tol: float = 1e-16) bool#
Checks that arrays are equal in shape and content
Returns
Trueif all arrays passed as arguments are of the same shape and all elements are equal within a given tolerancetol(for numeric elements) or exactly equal (for string elements), and returnsFalseotherwise. Inputs can be lists, tuples, NumPy arrays, numbers, strings, or nested arrays composed of any of these types.- Parameters:
item1 (list or tuple or np.ndarray or Number or str) – First array to evaluate
item2 (list or tuple or np.ndarray or Number or str) – Second item to evaluate
*args (list or tuple or np.ndarray or Number or str, optional) – Any other arrays to be evaluated
tol (float, optional) – Maximum difference between numeric values to consider equivalent (default is
1e-16)
- Returns:
Whether
item1,item2,*argshave the same shape, and all elements are equal within tolerancetol(for numeric elements) and exactly equal (for string elements)- Return type:
bool
Warning
The shape of the input arrays must be identical for the arrays to be considered equal. The shape of numbers is considered different from the shape of lists, so observe that
0and[0]are not considered equal in shape.By default, NumPy arrays are of homogeneous type. This means that, for instance,
pyxx.arrays.is_array_equal(np.array([1, 'a']), [1, 'a'])evaluates toFalse(because the NumPy array is converted to all strings). To avoid this issue, it is possible to create NumPy arrays with thedtype=objectargument and allow mixed types. For example,pyxx.arrays.is_array_equal(np.array([1, 'a'], dtype=object), [1, 'a'])evaluates toTrue.
Notes
Recursion Limit
Internally,
is_array_equal()is a recursive function. It is possible that for extremely large nested arrays, Python’s recursion limit may be reached. If this occurs and it is necessary to compare such a large array, consider increasing the recursion limit using the sys.setrecursionlimit() function.Purpose
One question that may arise is, why is this function necessary? NumPy already offers functions like numpy.array_equal(), numpy.isclose(), and numpy.allclose().
There are several main advantages of
is_array_equal():NumPy requires that arrays are numeric and are not “ragged” (sub-lists must all have the same length, recursively. For example, the array
x = [[1,2,3], [1,2]]is “ragged” sincelen(x[0]) != len(x[1])). In contrast,is_array_equal()can compare arrays with a mix of strings, numbers, lists, and tuples, as well as “ragged” arrays.The NumPy functions mentioned will typically throw an exception if the array sizes being compared differ, but
is_array_equal()simply returnsFalsein this case. This can eliminate the need to catch exceptions for certain applications.