What is the math.Min() Function in Golang

Golang math.Min() is a built-in function that “returns the smaller of two float64 values”.The math.Min() function accepts two float64 values as parameters and returns the minimum of the two.

To find a minimum of two numbers in Golang, you can use the “math.Min()” function.

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

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

We passed two values, 19.0 and 21.0 values to the math. Then, the min () function to find the minimum number of two.

From the output, we can see that 19.0 is the minimum number from two.

Example 2

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

The math.Min() function works with float64 and not with int64 values.

To find the minimum number from integers, convert the integers to float using the float64() function and then use the math.Min() 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

And we get the correct output.

Example 4

The math.Min() function helps us find the minimum of a slice of float64 values by comparing each value to the current minimum value.

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

In this example, we are creating a slice of float64 values and then assigning a minimum value to the first element of the slice.

Leave a Comment