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

ParameterTypeDescription
x1array_likeStarting value for finding the next representable floating-point number.
x2array_likeDirection towards which the next representable value of x1 is found. Must be broadcastable with x1.
outndarray, None, or tuple of ndarray and None, optionalOptional output array where the result is stored. If None, a new array is created.
wherearray_like, optionalBoolean mask specifying which elements to compute. Elements where where=False retain their original value.
castingstr, optionalDefines the casting behavior when computing the next representable value.
orderstr, optionalMemory layout order of the output array.
dtypedata-type, optionalDefines the data type of the output array.
subokbool, optionalDetermines 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