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
xis either (±)Inf orNAN, the return value will beNAN. -
The return value is
NANif the value of the second argument is either 0 orNAN. -
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 mainimport("fmt""math")func main() {var x float64 = 8.78var y float64 = 5.35z := 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
NaNfunction present in themathpackage to generate aNANvalue.
package mainimport("fmt""math")func main() {x := math.NaN()var y float64 = 5.35z := math.Mod(x,y)fmt.Print("The Remainder of ", x,"/", y, " is: ", z, "\n")x = 5.35y = math.NaN()z = math.Mod(x,y)fmt.Print("The Remainder of ", x,"/", y, " is: ", z)}