How to Use the math.Min() Function in Go

Golang math.Min() function is “used to find the smaller of two float64 values”. It accepts two float64 values as parameters and returns the minimum.

To add a math package to your program, use the “import” keyword to access the “Min()” function.

Syntax

func Min(x, y float64) float64

Parameters

It accepts two arguments from which we need to find a minimum number.

Return value

The Min() function returns -Inf if you pass -Inf to Min(-Inf, b) or Min(a, -Inf).

The Min() function returns NAN if you pass NAN to Min(NAN, b) or Min(a, NAN).

The Min() function returns -0 if -0 or 0 as in Min(-0, 0) or Min(0, -0).

Example 1: How to Use math.min() function

package main

import (
  "fmt"
  "math"
)

func main() {
  min := math.Min(19.0, 21.0)
  fmt.Println("The minimum number is: ", min)
}

Output

The minimum number is: 19

Example 2: Passing NaN, Inf, 0, -0

package main

import (
  "fmt"
  "math"
)

func main() {
  op1 := math.Min(0, -0)
  op2 := math.Min(math.NaN(), 21)
  op3 := math.Min(math.Inf(1), 19)

  fmt.Println("The minimum number is: ", op1)
  fmt.Println("The minimum number is: ", op2)
  fmt.Println("The minimum number is: ", op3)
}

Output

The minimum number is: 0
The minimum number is: NaN
The minimum number is: 19

Example 3: Using the float64() function

package main

import (
  "fmt"
  "math"
)

func main() {
  x := 19
  y := 21
  min := math.Min(float64(x), float64(y))
  fmt.Println("The minimum number is: ", min)
}

Output

The minimum number is: 19

Example 4: Finding minimum of float64 values in a slice

package main

import (
  "fmt"
  "math"
)

func main() {
  data := []float64{21.0, 29.0, 19.0, 46.0}
  min := data[0]
  for _, value := range data {
    min = math.Min(min, value)
  }
  fmt.Println("The minimum number is: ", min)
}

Output

The minimum number is: 19

That’s it!

Related posts

Golang Max Int

Golang int64 type

Golang math.Round()

Golang math.Ceil()