Book Image

NumPy: Beginner's Guide

By : Ivan Idris
Book Image

NumPy: Beginner's Guide

By: Ivan Idris

Overview of this book

Table of Contents (21 chapters)
NumPy Beginner's Guide Third Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
NumPy Functions' References
Index

Time for action – asserting arrays almost equal


Let's form arrays with the values from the previous Time for action section by adding a 0 to each array:

  1. Call the function with lower precision:

    print("Decimal 8", np.testing.assert_array_almost_equal([0, 0.123456789], [0, 0.123456780], decimal=8))

    The result is as follows:

    Decimal 8 None
    
  2. Call the function with higher precision:

    print("Decimal 9", np.testing.assert_array_almost_equal([0, 0.123456789], [0, 0.123456780], decimal=9))

    The test raises an AssertionError:

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

What just happened?

We compared two arrays with the NumPy array_almost_equal() function.

Have a go hero – comparing arrays with different shapes

Use the NumPy array_almost_equal() function to compare two arrays with different shapes.