Time for action – comparing arrays

Let's compare two arrays with the functions we just mentioned. We will reuse the arrays from the previous Time for action section and add a NaN to them:

  1. Call the array_allclose() function:
    print("Pass", np.testing.assert_allclose([0, 0.123456789, np.nan], [0, 0.123456780, np.nan], rtol=1e-7, atol=0))

    The result is as follows:

    Pass None
    
  2. Call the array_equal() function:
    print("Fail", np.testing.assert_array_equal([0, 0.123456789, np.nan], [0, 0.123456780, np.nan]))

    The test fails with an AssertionError:

    Fail
    Traceback (most recent call last):
    
    assert_array_compare
        raise AssertionError(msg)
    AssertionError:
    Arrays are not equal
    
    (mismatch 50.0%)
     x: array([ 0.        ,  0.12345679,         nan])
     y: array([ 0.        ,  0.12345678,         nan])

Get NumPy : Beginner's Guide - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.