Go math Package

Constants, rounding, powers, trigonometry, logarithms, and random numbers — the full numeric toolkit.

math.Pi · math.E Abs · Min · Max Floor · Ceil · Round Sqrt · Pow · Log Sin · Cos · Atan2 math/rand Inf · NaN
π

Constants

ℹ️
All math functions operate on float64. Constants are untyped so they adapt to any numeric context, but the functions themselves always take and return float64.
Mathematical constants Constants
math.Pi      // 3.141592653589793
math.E       // 2.718281828459045
math.Phi     // 1.618033988749895 (golden ratio)
math.Sqrt2   // 1.4142135623730951
math.SqrtE   // 1.6487212707001282
math.Ln2     // 0.6931471805599453
math.Log2E   // 1.4426950408889634
math.Log10E  // 0.4342944819032518
Size limits Limits
math.MaxFloat64   // 1.7976931348623157e+308
math.SmallestNonzeroFloat64 // 5e-324
math.MaxFloat32   // 3.4028234663852886e+38

math.MaxInt    // 9223372036854775807  (int on 64-bit)
math.MinInt    // -9223372036854775808
math.MaxInt8   // 127
math.MaxInt32  // 2147483647
math.MaxUint32 // 4294967295
🔢

Basic Functions

Abs, Min, Max, Mod, Dim Arithmetic
math.Abs(-7.5)          // 7.5
math.Abs(3.14)          // 3.14

math.Min(3.0, 5.0)      // 3
math.Max(3.0, 5.0)      // 5

// Mod — floating-point remainder (same sign as dividend)
math.Mod(10.5, 3.0)     // 1.5   (10.5 = 3*3 + 1.5)
math.Mod(-10.5, 3.0)    // -1.5  (sign follows dividend)

// Dim — max(x-y, 0)
math.Dim(5.0, 3.0)       // 2   (5-3=2 > 0)
math.Dim(3.0, 5.0)       // 0   (3-5=-2, clamp to 0)

// Note: for integers, use the built-in operators directly
// Go 1.21+ has min() and max() built-ins that work on integers too
x := min(3, 5)            // 3  (Go 1.21+ built-in)
y := max(3, 5)            // 5
🎯

Rounding

💡
Round rounds to the nearest integer, with ties going away from zero (i.e. 0.5 → 1, -0.5 → -1). To round to N decimal places, multiply, round, then divide.
Floor, Ceil, Round, Trunc Rounding
x := 3.7

math.Floor(x)    // 3  — round down (toward -∞)
math.Ceil(x)     // 4  — round up (toward +∞)
math.Round(x)    // 4  — nearest integer, ties away from zero
math.Trunc(x)    // 3  — truncate toward zero

// Negative numbers
math.Floor(-3.7) // -4
math.Ceil(-3.7)  // -3
math.Round(-3.5) // -4  (ties away from zero)
math.Trunc(-3.7) // -3  (toward zero)

// Round to 2 decimal places
round2 := func(v float64) float64 {
    return math.Round(v*100) / 100
}
round2(3.14159)  // 3.14
round2(2.675)    // 2.68
Modf — split into integer and fractional parts Modf
// Modf returns integer part and fractional part as float64
intPart, fracPart := math.Modf(3.75)
// intPart = 3.0,  fracPart = 0.75

intPart, fracPart = math.Modf(-3.75)
// intPart = -3.0, fracPart = -0.75

// Convert float64 to int safely
f := 42.9
n := int(math.Trunc(f))  // 42 — explicit truncation before int cast

Powers & Roots

Pow and Sqrt Powers
math.Pow(2, 10)    // 1024
math.Pow(9, 0.5)   // 3   (same as Sqrt(9))
math.Pow(2, -3)    // 0.125 (1/8)

math.Sqrt(16)      // 4
math.Sqrt(2)       // 1.4142135623730951
math.Sqrt(-1)      // NaN

math.Cbrt(27)      // 3  — cube root
math.Cbrt(-8)      // -2
Pow10 and Hypot Powers
// Pow10 — faster than Pow(10, n) for integers
math.Pow10(3)   // 1000
math.Pow10(-2)  // 0.01

// Hypot — Euclidean distance, avoids overflow
// Hypot(a, b) = Sqrt(a*a + b*b) without intermediate overflow
math.Hypot(3, 4)   // 5   (3-4-5 triangle)
math.Hypot(5, 12)  // 13
📈

Logarithms & Exponentials

Logarithms Log
// Natural logarithm (base e)
math.Log(math.E)    // 1
math.Log(1)         // 0
math.Log(0)         // -Inf
math.Log(-1)        // NaN

// Base-2 logarithm
math.Log2(8)        // 3
math.Log2(1024)     // 10

// Base-10 logarithm
math.Log10(100)     // 2
math.Log10(1000)    // 3

// Log of any base: Log_b(x) = Log(x) / Log(b)
log3of81 := math.Log(81) / math.Log(3)  // 4
Exponentials Exp
// Exp — e^x
math.Exp(1)          // 2.718281828459045
math.Exp(0)          // 1
math.Exp(-1)         // 0.36787944117144233

// Exp2 — 2^x
math.Exp2(8)         // 256
math.Exp2(10)        // 1024

// Expm1 — e^x - 1, more accurate near x=0
math.Expm1(0.0001)  // ~0.00010000500016667

// Log1p — ln(1+x), more accurate near x=0
math.Log1p(0.0001)  // ~0.00009999500033330
🔵

Trigonometry

ℹ️
All trig functions take angles in radians, not degrees. Multiply by math.Pi / 180 to convert degrees to radians.
Sin, Cos, Tan Trig
// Arguments in radians
math.Sin(0)              // 0
math.Sin(math.Pi / 2)    // 1
math.Cos(0)              // 1
math.Cos(math.Pi)        // -1
math.Tan(math.Pi / 4)    // 1

// Degree → radian conversion
deg := 90.0
rad := deg * math.Pi / 180
math.Sin(rad)             // 1

// Sincos — compute both at once (more efficient)
s, c := math.Sincos(math.Pi / 4)
// s ≈ 0.707, c ≈ 0.707
Inverse trig & Atan2 Inverse
math.Asin(1)          // π/2 ≈ 1.5708
math.Acos(1)          // 0
math.Atan(1)          // π/4 ≈ 0.7854

// Atan2(y, x) — angle of point (x,y) from origin, range (-π, π]
// Preferred over Atan(y/x) — handles all quadrants correctly
math.Atan2(1, 1)      // π/4   (45°, first quadrant)
math.Atan2(1, -1)     // 3π/4  (135°, second quadrant)
math.Atan2(-1, -1)    // -3π/4 (third quadrant)
math.Atan2(0, 1)      // 0

// Radian → degree
angleDeg := math.Atan2(1, 1) * 180 / math.Pi // 45
♾️

Special Values

⚠️
Never compare NaN with == — it never equals anything, including itself. Always use math.IsNaN(x).
Inf and NaN Special
// Inf — positive and negative infinity
posInf := math.Inf(1)    // +Inf
negInf := math.Inf(-1)   // -Inf

math.IsInf(posInf, 1)    // true  — is positive infinity?
math.IsInf(negInf, -1)   // true  — is negative infinity?
math.IsInf(posInf, 0)    // true  — is any infinity?
math.IsInf(42.0, 0)      // false

// NaN — Not a Number
nan := math.NaN()
math.IsNaN(nan)           // true
nan == nan                 // false — NaN != NaN, always!
math.IsNaN(math.Sqrt(-1)) // true
math.IsNaN(math.Log(-1))  // true
🎲

math/rand — Random Numbers

ℹ️
Go 1.20+ auto-seeds the global source, so you no longer need to call rand.Seed. For cryptographic randomness, use crypto/rand instead.
Random integers and floats math/rand
import "math/rand"

// Intn — random int in [0, n)
rand.Intn(10)         // 0–9
rand.Intn(100)        // 0–99

// Random int in [min, max)
min, max := 5, 15
n := min + rand.Intn(max-min)  // 5–14

// Float64 — random float in [0.0, 1.0)
rand.Float64()         // e.g. 0.6046602879796196

// Float64 in [lo, hi)
lo, hi := 1.5, 3.5
f := lo + rand.Float64()*(hi-lo)

// Int63, Int31 — full-range random integers
rand.Int63()           // random int64 in [0, 2^63)
rand.Int31()           // random int32 in [0, 2^31)
Shuffle — randomize a slice Shuffle
deck := []string{"A", "2", "3", "4", "5"}

rand.Shuffle(len(deck), func(i, j int) {
    deck[i], deck[j] = deck[j], deck[i]
})
// deck is now in random order
Seeded source (reproducible) Seeded
// Use a local source for reproducible sequences (tests, simulations)
src := rand.NewSource(42)
rng := rand.New(src)

rng.Intn(100)    // always same sequence for seed 42
rng.Float64()
rng.Shuffle(len(deck), func(i, j int) {
    deck[i], deck[j] = deck[j], deck[i]
})
crypto/rand — cryptographically secure random bytes crypto/rand
import (
    "crypto/rand"
    "math/big"
)

// Read random bytes directly
buf := make([]byte, 16)
rand.Read(buf)   // fills buf with cryptographically random bytes

// Secure random integer in [0, max)
max := big.NewInt(100)
n, err := rand.Int(rand.Reader, max)
// n is a *big.Int in [0, 100)
📋

Quick Reference

Function Returns Description
math.Abs(x)float64Absolute value of x
math.Min(x, y)float64Smaller of x and y
math.Max(x, y)float64Larger of x and y
math.Mod(x, y)float64Floating-point remainder x/y
math.Dim(x, y)float64max(x-y, 0)
math.Floor(x)float64Round down toward -∞
math.Ceil(x)float64Round up toward +∞
math.Round(x)float64Round to nearest; ties away from zero
math.Trunc(x)float64Truncate toward zero
math.Modf(x)int, frac float64Split into integer and fractional parts
math.Sqrt(x)float64Square root; NaN if x < 0
math.Cbrt(x)float64Cube root
math.Pow(x, y)float64x^y
math.Pow10(n)float6410^n (integer exponent)
math.Hypot(p, q)float64√(p²+q²) without overflow
math.Log(x)float64Natural logarithm ln(x)
math.Log2(x)float64Base-2 logarithm
math.Log10(x)float64Base-10 logarithm
math.Exp(x)float64e^x
math.Exp2(x)float642^x
math.Sin(x)float64Sine of x (radians)
math.Cos(x)float64Cosine of x (radians)
math.Tan(x)float64Tangent of x (radians)
math.Sincos(x)sin, cos float64Both sin and cos in one call
math.Asin(x)float64Arcsine, result in [-π/2, π/2]
math.Acos(x)float64Arccosine, result in [0, π]
math.Atan(x)float64Arctangent, result in (-π/2, π/2)
math.Atan2(y, x)float64Angle of (x,y) from origin; result in (-π, π]
math.Inf(sign)float64+Inf (sign≥0) or -Inf (sign<0)
math.NaN()float64IEEE 754 not-a-number
math.IsInf(f, sign)boolTrue if f is ±Inf
math.IsNaN(f)boolTrue if f is NaN
Function (math/rand) Returns Description
rand.Intn(n)intRandom int in [0, n)
rand.Int63()int64Random non-negative int64
rand.Float64()float64Random float64 in [0.0, 1.0)
rand.Float32()float32Random float32 in [0.0, 1.0)
rand.Shuffle(n, swap)Randomly permute n elements
rand.NewSource(seed)SourceCreate a seeded random source
rand.New(src)*RandCreate a Rand from a source