Numpy is a great python package for manipulating NumPy arrays. It allows you to do complex parts of the mathematical calculation easily. For this there are many functions in it and numpy allClose() is one of them. In this entire tutorial, you will learn how to implement NumPy allClose() through steps.
Syntax of the Numpy allClose()
Before going to the coding demonstration part first lets know the syntax of the numpy allClose() method. Below it is .
numpy.allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)
The explanation of the parameters is below.
a,b: It is the input arrays to compare.
rtol: The relative tolerance parameter of float type.
atol: The absolute tolerance parameter of float type.
equal_nan: Whether to compare NaN’s as equal. If True, NaN’s in a will be considered equal to NaN’s in b in the output array.
You will get True as the output if the two arrays are equal within the given tolerance otherwise the output will be false.
Steps to implement Numpy allClose method
In this section, you will know all the steps to implement numpy allClose method. Just follow all the steps for a clear understanding.
Step 1: Import required libraries
The first step is to import all the necessary libraries for implementing allClose() method. Let’s import it using the import statement.
import numpy as np
Step 2: Create a Sample Numpy array
Now the next step is to create a dummy array for implementing the allClose() method. In NumPy, you can create a NumPy array using the numpy.array() method. Let’s create it.
numpy_array_a = np.array([[1,2,3],[4,5,6]]) numpy_array_b = np.array([[1,2,3],[4,5,6]])
Step 3: Implement the numpy allClose() method
After the creation of the NumPy array, let’s use the allClose() method. Execute the below lines of code and see the output.
import numpy as np numpy_array_a = np.array([[1,2,3],[4,5,6]]) numpy_array_b = np.array([[1,2,3],[4,5,6]]) print(np.allclose(numpy_array_a,numpy_array_b))
In the above code, rtol has not been used. But if you use it then you will get different results. For example, If rtol is 1 then the elements that have a difference of 1 then it is true otherwise it is false. Run the below lines of code and see the output.
import numpy as np numpy_array_a = np.array([[10,12,7],[4,5,6]]) numpy_array_b = np.array([[1,2,3],[4,5,6]]) print(np.allclose(numpy_array_a,numpy_array_b,atol=1))
Numpy is a great python package for complex mathematical calculations. There are steps to implement allClose() method in python. I hope you have liked this tutorial. If you have any queries then you can contact us for more help.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.