What is the Remainder function in Golang?

The Remainder function is used to find the IEEE 754 floating-point remainder from the floating-point division of the two passed arguments (x/y).

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

Function definition

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

Parameters

The Remainder function takes two arguments of type float64:

  • x: This argument represents the numerator in the division that will take place to find the remainder.

  • y: This argument represents the denominator in the division that will take place to find the remainder.

Return value

The Remainder function returns a single value of type float64 that represents the IEEE 754 floating-point remainder of the division x/y.

Some special cases:

  • If the argument has a +Inf value, the return value will be 0.

  • If the value of x is either (±)Inf or NAN, the return value will be NAN.

  • The return value is NAN if the value of the second argument is either 0 or NAN.

  • If (±)Inf is passed as the second argument, the return value is x (first argument).

Code

Below is a simple example where we find out the IEEE 754 floating-point remainder of two float numbers.

package main
import(
"fmt"
"math"
)
func main() {
var x float64 = 8.78
var y float64 = 5.35
z := math.Remainder(x,y)
fmt.Print("The IEEE 754 Remainder of ", x,"/", y, " is: ", z)
}

The example below shows how the Remainder function handles NAN values in its arguments.

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

package main
import(
"fmt"
"math"
)
func main() {
x := math.NaN()
var y float64 = 5.35
z := math.Remainder(x,y)
fmt.Print("The IEEE 754 Remainder of ", x,"/", y, " is: ", z, "\n")
x = 5.35
y = math.NaN()
z = math.Remainder(x,y)
fmt.Print("The IEEE 754 Remainder of ", x,"/", y, " is: ", z)
}

Free Resources