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.
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.
numpy.nextafter(arr1, arr2, out=None, *, where=True,)
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 of arr1
should 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.The method numpy.nextafter()
returns arr1
's next representable values in the direction of arr2
. It can be float or ndarray.
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)
numpy
library.arr1
and arr2
.np.nextafter()
method is used to compute the arr1
's next representable values in the direction of arr2
.nextafter()
in 2D arraysThe np.nextafter()
method works like this for a 2D array:
The element 10
at index(0,0) of arr1
is calculated against 1
at index(0,0) of arr2
.
The element 1
at index(0,1) of arr1
is calculated against -np.inf
at index(1,0)
of arr2
.
The element 4
at index(1,0) of arr1
is calculated against 0
at index (0,1) of arr2
.
The element 0.5
at index (1,1) of arr1
is calculated against +np.inf
at index(1,1) of arr2
.