Golang math.Dim() Function

Golang math.Dim() function returns the “maximum of x-y or 0.”

Syntax

func Dim(x, y float64) float64

Parameters

x, y: The values to get the maximum of x-y or 0.

Return value

The Dim() function returns a single value of type float64. This value represents the difference between the two arguments (x-y) and 0.

  1. Dim(+Inf, +Inf) = NaN: If both parameters are positive infinity, the function returns the Inf.
  2. Dim(-Inf, -Inf) = NaN: If both parameters are negative infinity, the function returns the Inf.
  3. Dim(x, NaN) = Dim(NaN, x) = NaN: If any of the parameters is NaN (Not-A-Number), the function returns the NaN.

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

package main

import (
  "fmt"
  "math"
)

func main() {
  fmt.Println(math.Dim(5, 3))
  fmt.Println(math.Dim(3, 5))
  fmt.Println(math.Dim(5, 5))
  fmt.Println(math.Dim(5, math.NaN()))
}

Output

2
0
0
NaN

Example 2: Calculate the Remaining Space

package main

import (
  "fmt"
  "math"
)

func main() {
  shelfLength := 10.0
  boxLength := 6.5

 remainingSpace := math.Dim(shelfLength, boxLength)
 fmt.Printf("After placing a box of length %.2f on a shelf of length %.2f, the remaining space is %.2f units.\n",
            boxLength, shelfLength, remainingSpace)
}

Output

After placing a box of length 6.50 on a shelf of length 10.00, the remaining space is 3.50 units.

Example 3: Calculate the Elevation Difference

package main

import (
  "fmt"
  "math"
)

func main() {
  mountainA := 4500.0
  mountainB := 4200.0

  elevationDifference := math.Dim(mountainA, mountainB)
  fmt.Printf("The elevation difference between Mountain A and Mountain B is %.2f meters.\n", elevationDifference)
}

Output

The elevation difference between Mountain A and Mountain B is 300.00 meters.

Example 4: Passing negative arguments

package main

import (
  "fmt"
  "math"
)

func main() {
  data := math.Dim(-19, -21)
  fmt.Println(data)
}

Output

2

Example 5: Passing zero/zero

package main

import (
  "fmt"
  "math"
)

func main() {
  zero := 0.0
  output := math.Dim(zero/zero, 3)
  fmt.Println(output)
}

Output

NaN

That’s it!

Related posts

Golang math.Cbrt()

Golang math.Pow()

Golang math.Ceil()

Golang math.Min()

Golang math.Floor()

Golang math.Round()

Golang math.Mod()

Leave a Comment