What is the Nextafter function in Golang?

The Go programming language uses the Nextafter function to find the next representable float64 value between the two arguments it is given, x and y. Nextafter returns the number immediately after x and between x and y.

To use this function, you must import the math package in your file and access the Nextafter function within it using the . notation (math.Nextafter). Here, Nextafter is the actual function, while math is the Go package that stores the definition of this function.

Function definition

The definition of the Nextafter function inside the math package is as follows:

Parameters

The Nextafter function takes two arguments of type float64:

  • x: An argument of type float64. The Nextafter function finds the next representable float64 value after x.

  • y: An argument of type float64. The Nextafter function finds the next representable float64 value after x that is in the direction of y.

Return value

The Nextafter function returns a single value of type float64 that represents the next representable float64 number after x that is in the direction of y.

Some special cases are when you pass something that is infinity, 0, or NAN as an argument:

  • If both arguments are the same value, let’s say x, then Nextafter returns that value x.
  • If either of the two arguments is of type NAN, then the return value is also NAN.

Code

Below is a simple example where we find out the next representable float64 number after 5.355.35 in the direction of 11:

package main
import(
"fmt"
"math"
)
func main() {
var x float64 = 5.35
y := math.Nextafter(x,1)
fmt.Print("The next representable float64 after ", x," is ", y)
}

The example below demonstrates how the Nextafter function handles NAN values.

Here, we use the NaN function in the math package to generate a NAN value.

package main
import(
"fmt"
"math"
)
func main() {
my_nan := math.NaN()
y := math.Nextafter(my_nan,1)
fmt.Print("The next representable float64 after ", my_nan," is ", y)}

Free Resources