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 typefloat64. TheNextafterfunction finds the next representablefloat64value afterx. -
y: An argument of typefloat64. TheNextafterfunction finds the next representablefloat64value afterxthat is in the direction ofy.
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, thenNextafterreturns that valuex. - If either of the two arguments is of type
NAN, then the return value is alsoNAN.
Code
Below is a simple example where we find out the next representable float64 number after in the direction of :
package mainimport("fmt""math")func main() {var x float64 = 5.35y := 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
NaNfunction in themathpackage to generate aNANvalue.
package mainimport("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)}