Golang modulo: How to Use the Mod() Function in Go

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

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 1: Golang program to calculate the modulo

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

Example 2:  Handling NaN values in Mod() Function

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

That’s it!