NumPy nextafter()
The numpy.nextafter()
function returns the next representable floating-point value after x1
towards x2
, element-wise.
This function is useful for exploring floating-point precision and determining the smallest increment in a given direction.
Syntax
</>
Copy
numpy.nextafter(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)
Parameters
Parameter | Type | Description |
---|---|---|
x1 | array_like | Starting value for finding the next representable floating-point number. |
x2 | array_like | Direction towards which the next representable value of x1 is found. Must be broadcastable with x1 . |
out | ndarray, None, or tuple of ndarray and None, optional | Optional output array where the result is stored. If None, a new array is created. |
where | array_like, optional | Boolean mask specifying which elements to compute. Elements where where=False retain their original value. |
casting | str, optional | Defines the casting behavior when computing the next representable value. |
order | str, optional | Memory layout order of the output array. |
dtype | data-type, optional | Defines the data type of the output array. |
subok | bool, optional | Determines if subclasses of ndarray are preserved in the output. |
Return Value
Returns an array with the next representable floating-point values of x1
in the direction of x2
. If both inputs are scalars, a scalar is returned.
Examples
1. Finding the Next Floating-Point Number
Here, we find the next floating-point number after 1.0 in the direction of 2.0.
</>
Copy
import numpy as np
# Define values
x1 = 1.0
x2 = 2.0
# Compute next floating-point number after x1 towards x2
result = np.nextafter(x1, x2)
# Print the result
print("Next representable number after 1.0 towards 2.0:", result)
Output:
Next representable number after 1.0 towards 2.0: 1.0000000000000002

2. Moving in the Opposite Direction
We compute the next representable number after 1.0 in the direction of 0.0.
</>
Copy
import numpy as np
# Define values
x1 = 1.0
x2 = 0.0
# Compute next floating-point number after x1 towards x2
result = np.nextafter(x1, x2)
# Print the result
print("Next representable number after 1.0 towards 0.0:", result)
Output:
Next representable number after 1.0 towards 0.0: 0.9999999999999999
