How to use the numpy.nextafter() method for 2D array in Python
The numpy.nextafter()method calculates the next floating-point value after the value of x1, towards another value of x2. This is done element by element.
How does numpy.nextafter() work?
It takes the first argument’s value to identify the next representable value, and the second argument indicates the direction to search for the next representable or floating-point value.
Note: In Python, a list of lists can be used to create a two-dimensional (2D) array.
Syntax
numpy.nextafter(arr1, arr2, out=None, *, where=True,)
Parameters
arr1: This is the input array of values to which the next representable value will be delivered.arr2: This specifies the direction in which the next representable value ofarr1should be searched.out: This is an optional parameter. It specifies the location where the result is saved.where: This is an optional parameter. It represents the condition in which the input gets broadcasted.
Return value
The method numpy.nextafter() returns arr1's next representable values in the direction of arr2. It can be float or ndarray.
Example
Let’s assume we want to find the next representation of the value x= 9.45 in the direction of y= -1
print(np.nextafter(x,y))
Output: 9.449999999999998
Now, let’s use an array arr1 = [9.45], arr2 = [-1]
print(np.nextafter(arr1,arr2))
Output: [9.45]
We’ll notice that the result was approximated. This is because Python displays the decimal approximation instead of the true decimal value when displaying arrays.
The same result is applicable to a 2D array.
The following code shows how to use the numpy.nextafter() method for two-dimensional(2D) arrays.
# Import numpyimport numpy as np# Create 2D arraysarr1 = np.array([[10,1],[4,0.5]])arr2 = np.array([[1,0],[-np.inf,+np.inf]])# compute the arr1's next representable values in the direction of arr2.# and store the result in resultresult = np.nextafter(arr1,arr2)print(result)
Code explanation
- Line 2: We import the
numpylibrary. - Lines 5 to 6: We create two separate 2D arrays,
arr1andarr2. - Line 10: The
np.nextafter()method is used to compute thearr1's next representable values in the direction ofarr2. - Line 12: Finally, we display the result.
Working of nextafter() in 2D arrays
The np.nextafter() method works like this for a 2D array:
-
The element
10at index(0,0) ofarr1is calculated against1at index(0,0) ofarr2. -
The element
1at index(0,1) ofarr1is calculated against-np.infatindex(1,0)ofarr2. -
The element
4at index(1,0) ofarr1is calculated against0at index (0,1) ofarr2. -
The element
0.5at index (1,1) ofarr1is calculated against+np.infat index(1,1) ofarr2.