big.Int, big.Float, and big.Rat
suggest changeStandard numeric types in Go have fixed capacities: int64 and uint64 overflow beyond 64 bits, while float64 suffers from IEEE-754 binary floating-point rounding errors (for instance, 0.1 + 0.2 != 0.3).
For financial calculations, cryptography, number theory, and scientific computing where arbitrary precision is required, Go's standard library provides the math/big package with three core types:
big.Int: Arbitrary-precision signed integers (unlimited size).big.Float: Arbitrary-precision floating-point numbers with configurable bit precision and rounding modes.big.Rat: Exact rational numbers represented as reduced fractions ($p/q$).
1. big.Int (Arbitrary-Precision Integers)
Creation and Parsing
Because big.Int values can exceed 64-bit integer limits, they are often initialized from decimal or hexadecimal strings:
package main
import (
"fmt"
"math/big"
)
func main() {
// From int64
a := big.NewInt(1_000_000_000_000)
// From string (base 10)
b := new(big.Int)
b.SetString("99999999999999999999999999999999999999999999999999", 10)
fmt.Println("Integer a:", a)
fmt.Println("Large integer b:", b.String())
}
Arithmetic Operations (The Receiver Pattern)
In math/big, methods modify their receiver and return it to allow call chaining: z.Add(x, y) sets $z = x + y$ and returns pointer z:
package main
import (
"fmt"
"math/big"
)
func main() {
x := big.NewInt(50)
y := big.NewInt(15)
// Addition: z = x + y
sum := new(big.Int).Add(x, y)
// Subtraction: z = x - y
diff := new(big.Int).Sub(x, y)
// Multiplication: z = x * y
prod := new(big.Int).Mul(x, y)
// Quotient and Remainder: div = x / y, rem = x % y
quo, rem := new(big.Int), new(big.Int)
quo.QuoRem(x, y, rem)
fmt.Printf("Sum: %s, Diff: %s, Prod: %s, Quo: %s, Rem: %s\n",
sum, diff, prod, quo, rem)
}
Cryptographic and Modular Arithmetic
big.Int provides built-in modular arithmetic and primality testing:
// Modular exponentiation: result = (base ^ exp) mod m
base := big.NewInt(7)
exp := big.NewInt(256)
mod := big.NewInt(13)
result := new(big.Int).Exp(base, exp, mod)
fmt.Println("7^256 mod 13 =", result)
// Primality check: Miller-Rabin probabilistic test (n=20 checks)
candidate := big.NewInt(104729)
isPrime := candidate.ProbablyPrime(20)
fmt.Println("Is prime:", isPrime) // true
Comparisons
Use x.Cmp(y) which returns -1 if $x < y$, 0 if $x == y$, and +1 if $x > y$:
if x.Cmp(y) > 0 {
fmt.Println("x is strictly greater than y")
}
2. big.Float (Arbitrary-Precision Floating-Point)
big.Float supports floating-point math with user-configurable mantissa precision.
package main
import (
"fmt"
"math/big"
)
func main() {
// Set 256 bits of mantissa precision (default is 53, like float64)
prec := uint(256)
// Parse high-precision decimal strings
pi, _, _ := new(big.Float).SetPrec(prec).Parse("3.14159265358979323846264338327950288419716939937510", 10)
r, _, _ := new(big.Float).SetPrec(prec).Parse("2.5", 10)
// Area = pi * r^2
rSquared := new(big.Float).Mul(r, r)
area := new(big.Float).Mul(pi, rSquared)
// Format to 40 decimal places
fmt.Printf("Circle area: %s\n", area.Text('f', 40))
}
Warning: Never initialize
big.Floatfrom a primitivefloat64literal (e.g.big.NewFloat(0.1)), because the binary approximation error infloat64is copied intobig.Float. Always parse from string via.SetString("0.1").
3. big.Rat (Exact Rational Numbers / Fractions)
big.Rat represents rational numbers as exact quotients of two integers: $\frac{\text{Numerator}}{\text{Denominator}}$. Fractions are automatically reduced to lowest terms:
package main
import (
"fmt"
"math/big"
)
func main() {
// a = 1/3
a := big.NewRat(1, 3)
// b = 1/6
b := big.NewRat(1, 6)
// Exact sum: 1/3 + 1/6 = 3/6 = 1/2
c := new(big.Rat).Add(a, b)
fmt.Println("Exact fraction:", c.String()) // Output: 1/2
fmt.Println("Numerator:", c.Num()) // Output: 1
fmt.Println("Denominator:", c.Denom()) // Output: 2
// Render as decimal string with 4 digits:
fmt.Println("Decimal:", c.FloatString(4)) // Output: 0.5000
}
big.Rat avoids binary floating-point rounding errors entirely, making it ideal for currency conversions and financial ratios.
4. Memory Optimization and Zero-Allocation Loops
In tight loops, reallocating new(big.Int) on every iteration causes garbage collection pressure. Reuse an existing variable as both the accumulator and destination:
func factorial(n int64) *big.Int {
result := big.NewInt(1)
multiplier := new(big.Int)
for i := int64(2); i <= n; i++ {
multiplier.SetInt64(i)
result.Mul(result, multiplier) // Reuses 'result' buffer in-place
}
return result
}
Summary Comparison
| Type | Representation | Typical Use Case | Prevents |
|---|---|---|---|
big.Int |
Sign and arbitrary-length magnitude | RSA cryptography, blockchain addresses, large combinatorics | 64-bit integer overflow |
big.Float |
Sign, exponent, arbitrary-precision mantissa | Scientific simulations, high-precision astronomy calculations | Inadequate mantissa precision |
big.Rat |
Reduced fraction ($p/q$) | Financial ledgers, currency conversions, exact probabilities | Floating-point rounding inaccuracies |