math/big

Guided tour · Math · pkg.go.dev →

Arbitrary-precision integers (Int), rationals (Rat), and floats (Float). No overflow, at the cost of allocation.

Int — arbitrary-precision integers

Go operators don't work — you call methods that write into a receiver. The result is always the receiver, which is returned for chaining.

Factorial — canonical big.Int example

fact := big.NewInt(1)
for i := int64(1); i <= 100; i++ {
    fact.Mul(fact, big.NewInt(i))
}
fmt.Println(fact.String())

Modular exponentiation for crypto-ish math

result := new(big.Int).Exp(base, exp, mod)

Parse from a string

n, ok := new(big.Int).SetString("123456789012345678901234567890", 10)
fmt.Println(n, ok)

Rat — arbitrary-precision rationals

Exact fractions

r := big.NewRat(1, 3)
r.Add(r, big.NewRat(1, 6))
fmt.Println(r.String())    // 1/2

Float — arbitrary-precision floating-point

High-precision math

f := new(big.Float).SetPrec(200).SetFloat64(1.0)
f.Quo(f, big.NewFloat(7))
fmt.Println(f.Text('f', 50))