Skip to content

Go Math Package

The math package provides standard mathematical constants and functions. It works primarily with the float64 type.

1. Common Constants

package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Println(math.Pi)   // 3.14159...
    fmt.Println(math.E)    // 2.71828...
    fmt.Println(math.Phi)  // 1.61803...
}

2. Basic Functions

  • math.Abs(x): Absolute value.
  • math.Max(x, y): Maximum of two numbers.
  • math.Min(x, y): Minimum of two numbers.
  • math.Sqrt(x): Square root.
  • math.Pow(x, y): x to the power of y.
fmt.Println(math.Max(10, 20)) // 20
fmt.Println(math.Sqrt(16))     // 4

3. Rounding

  • math.Floor(x): Rounds down to nearest integer.
  • math.Ceil(x): Rounds up to nearest integer.
  • math.Round(x): Rounds to the nearest integer (0.5 rounds away from zero).
fmt.Println(math.Floor(3.8)) // 3
fmt.Println(math.Ceil(3.1))  // 4

4. Special Values

Go treats things like "Not a Number" (NaN) and Infinity as valid float64 values.

1
2
3
4
inf := math.Inf(1)  // Positive Infinity
nan := math.NaN()   // Not a Number

fmt.Println(math.IsNaN(nan)) // true

Best Practices

  1. Floating-Point Accuracy: Remember that 0.1 + 0.2 might not exactly equal 0.3 due to how computers store decimals. For money, use an int (cents) or a specialized decimal library.
  2. Explicit Conversion: If you have an int, you must convert it to float64 before using math functions: math.Sqrt(float64(myInt)).
  3. Trigonometry: Functions like math.Sin and math.Cos expect radians, not degrees.