What is the Mod function in Golang?

The Mod function is used to find the modulus or remainder from the floating-point division of the two arguments (x/y).

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

Function definition

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

Parameters

The Mod 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 Mod function returns a single value of type float64 that represents the 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 remainder of two float numbers.

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

The example below shows how the Mod 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.Mod(x,y)
fmt.Print("The Remainder of ", x,"/", y, " is: ", z, "\n")
x = 5.35
y = math.NaN()
z = math.Mod(x,y)
fmt.Print("The Remainder of ", x,"/", y, " is: ", z)
}

Free Resources