Go📦Standard Libraryintermediate
math and math/rand — Numbers
Go · Standard Library · Run with go run
Explanation
The `math` package provides floating-point constants (`math.Pi`, `math.MaxInt64`) and functions (`Sqrt`, `Pow`, `Floor`, `Abs`, `Min`, `Max`). The `math/rand` package generates pseudo-random numbers; `math/rand/v2` (Go 1.22+) modernizes the API with better defaults and no global seeding required. For security-sensitive randomness, use `crypto/rand` instead.
Real-World Scenario
A simulation needs to model dice rolls and compute geometric distances. `rand.IntN(6)+1` rolls a die; `math.Hypot(dx, dy)` computes the Euclidean distance between two points without overflow.
Quick Snippet
snippet.go
import (
"math"
"math/rand/v2"
)
math.Sqrt(144) // 12
math.Pow(2, 10) // 1024
math.Max(3.0, 7.0) // 7
math.Abs(-4.5) // 4.5
math.Pi // 3.141592653589793
// math/rand/v2 — no manual seeding needed
rand.IntN(100) // random int in [0, 100)
rand.Float64() // random float in [0.0, 1.0)Full Example
math_pkg.go
// Compile: go run math_pkg.go
// Output:
// sqrt(144) = 12
// pow(2,10) = 1024
// max(3,7) = 7
// abs(-4.5) = 4.5
// hypot(3,4) = 5
// random in range: true
package main
import (
"fmt"
"math"
"math/rand/v2"
)
func main() {
fmt.Println("sqrt(144) =", math.Sqrt(144))
fmt.Println("pow(2,10) =", math.Pow(2, 10))
fmt.Println("max(3,7) =", math.Max(3, 7))
fmt.Println("abs(-4.5) =", math.Abs(-4.5))
fmt.Println("hypot(3,4) =", math.Hypot(3, 4))
r := rand.IntN(100) // [0, 100)
fmt.Println("random in range:", r >= 0 && r < 100)
}
Run command
go run math_pkg.go