PyTorch .nextafter()
The torch.nextafter() function returns the next representable floating-point value of each element in the input tensor in the direction of the corresponding element in the other tensor.
It’s useful for precise floating-point control, such as numerical stability adjustments or boundary value analysis.
Note: If an element in
inputequals the corresponding element inother, that element is returned unchanged in the output tensor.
Syntax
torch.nextafter(input, other, out=None)
Parameters:
input(Tensor): The input tensor containing starting floating-point values.other(Tensor): The tensor indicates each element’s direction ininput.out(Tensor, optional): The output tensor to store results. If not provided, a new tensor is returned.
Return value:
Returns a tensor of the same shape as input, where each element is the next representable floating-point value of input in the direction of other.
Example
The following example shows how torch.nextafter() moves each element of one tensor slightly closer to the corresponding element in another tensor:
import torch# Create input tensors (float type)input_tensor = torch.tensor([1.0, 5.0, -10.0, 8.0])other_tensor = torch.tensor([2.0, 1.0, -11.0, 8.0])# Calculate nextafterresult = torch.nextafter(input_tensor, other_tensor)print("Input Tensor:")print(input_tensor)print("\nOther Tensor:")print(other_tensor)print("\nResult Tensor:")print(result)
The output of the code is:
Input Tensor:tensor([ 1., 5., -10., 8.])Other Tensor:tensor([ 2., 1., -11., 8.])Result Tensor:tensor([ 1.0000, 5.0000, -10.0000, 8.0000])
In this:
1.0becomes slightly larger since it moves toward2.0.5.0becomes slightly smaller since it moves toward1.0.-10.0becomes slightly more negative since it moves toward-11.0.8.0remains unchanged since it already equals the corresponding value.
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PyTorch on Codecademy
- Learn how to use PyTorch to build, train, and test artificial neural networks in this course.
- Intermediate.3 hours