What is Mod() Function in Golang

You can use the math.Mod() function to calculate the modulus or remainder from the floating-point division of the two arguments in Golang. To use the Mod() function, you need to import the math package to your file and access the Mod() function within it using the (.) notation.

Syntax

func Mod(x, y float64) float64

Parameters

The Mod() function takes two arguments of type float64:

  1. x: It represents the numerator in the division that will take place to find the remainder.
  2. y: It represents the denominator in the division that will take place to find the remainder.

Return value

The math.Mod() function returns the floating-point remainder of x/y.

The magnitude of the result is less than y, and its sign agrees with that of x.

There are some of the following cases.

  1. If the argument has a +Inf value, the return value will be 0.
  2. If the value of x is either (±)Inf or NAN, the return value will be NAN.
  3. The return value is NAN if the value of the second argument is either 0 or NAN.
  4. If (±)Inf is passed as the second argument, the return value is x.

Example

package main

import (
  "fmt"
  "math"
)

func main() {
  var x float64 = 21.19
  var y float64 = 19.21

  result := math.Mod(x, y)
  fmt.Println("The Remainder of ", x, "/", y, " is:", result)
}

Output

The Remainder of 21.19 / 19.21 is: 1.9800000000000004

The above code uses math.Mod() function from the math package to perform the modulo operation on two floating-point numbers, x, and y.

The math.Mod() function takes two float64 arguments and returns the floating-point remainder of x/y.

In this example, the value of x is 21.19, and y is 19.21. When x is divided by y, the result is 1.98, so the math.Mod() function returns 1.98.

It’s important to note that math.Mod() function returns a floating-point number, which might not be exact in some cases, especially with large numbers or when working with decimal places.

How to handle NaN values in Golang Mod()

If you pass the NaN value to the math.Mod() function, returns the NaN value.

To get the NaN value in Golang, use math.NaN() function.

package main

import (
  "fmt"
  "math"
)

func main() {
  var x float64 = 21.19
  var y float64 = math.NaN()

  result := math.Mod(x, y)
  fmt.Println("The Remainder of ", x, "/", y, " is:", result)
}

Output

The Remainder of 21.19 / NaN is: NaN

You can see that If the math.Mod() function encounters the NaN value of any variable, it returns NaN as output.

Conclusion

The modulus in Go (Golang) refers to the remainder of a division operation between two numbers. The math.Mod() function is a helpful function in Golang for performing modulo operations on floating-point numbers.

Leave a Comment