Skip to content
Tutorials Center
My learning

Topics

Lesson 93 of 147 ยท Standard Library

math/big: Big Integers, Rationals and Floats

Do arbitrary-precision arithmetic in Go with math/big - big.Int, big.Rat and big.Float, the receiver pattern, factorials, Fibonacci, modular math, primes and exact fractions.

Go's int64 tops out at 9,223,372,036,854,775,807. That is plenty for counting things, but not for factorials, cryptography keys or exact money calculations. Floating-point numbers have the opposite problem: they cover a huge range but only about 15 to 16 significant digits, and values like 0.1 cannot be stored exactly.

The math/big package gives you three types with no fixed size limit: big.Int for whole numbers, big.Rat for exact fractions and big.Float for decimals with a precision you choose. They are slower than the built-in types, so use them only when you need what they offer. For ordinary numbers, see Math and Random.

big.Int and the receiver pattern

A *big.Int is a pointer to a number that can grow as large as memory allows. You create one with big.NewInt(n) for small values, or with SetString for text.

Arithmetic methods look unusual. They do not return a new number; they store the result in the receiver and return the receiver, so you can chain calls. z.Add(x, y) means z = x + y:

Go Basic big.Int arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Why the odd design? It lets you reuse memory. Allocating a new number for every step of a loop would be wasteful, so you can write sum.Add(sum, x) and reuse sum. The result of a method may even be one of its own arguments, as long as you remember the order: receiver first.

Cmp returns -1, 0 or +1 (less, equal, greater), and Sign does the same relative to zero. Two methods exist for division: Quo and Rem truncate toward zero, like Go's / and % on ordinary integers, while Div and Mod use Euclidean division, where the remainder is never negative. If a value fits, convert it back with Int64() or Uint64(), and use IsInt64() first to check that it does.

flowchart LR
    X["x"] --> OP["z.Add(x, y)"]
    Y["y"] --> OP
    OP --> Z["z holds x + y"]
    Z --> RET["and z is returned<br/>so calls can be chained"]

The receiver z is both where the answer is stored and what the method returns.

Factorials and Fibonacci

Big integers shine when numbers explode. A loop that multiplies in place computes a factorial that int64 could never hold. Here Mul(f, x) is written into f itself, which is the efficient pattern:

Go Factorials and Fibonacci numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

20! is the last factorial that fits in a signed 64-bit integer. The String() method gives the decimal text, Text(base) any base, and BitLen() the number of bits. fmt also understands verbs such as %d, %x and %s for *big.Int.

Modular arithmetic and primes

Public-key cryptography relies on huge numbers combined with modulus operations. Exp(x, y, m) computes x^y mod m efficiently without ever building the giant intermediate power (if m is nil or zero, it returns plain x^y). Other helpers include GCD, ModInverse, Sqrt and ProbablyPrime(n):

Go Exp, GCD, ModInverse and primality

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

ProbablyPrime(n) runs a strong test with n extra rounds. It never calls a prime composite, and the chance of calling a composite number prime is at most 4 to the power of minus n. For real security keys, use crypto/rand and the crypto/rsa or crypto/ecdsa packages instead of rolling your own (see Crypto and Hashing).

big.Rat: exact fractions

float64 cannot represent 0.1, so 0.1 + 0.2 is not exactly 0.3. A big.Rat stores a fraction as a numerator and denominator, always reduced, so the arithmetic is exact:

Go Exact fractions with big.Rat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Rat is a good choice for money in cents or for any calculation where rounding errors are unacceptable. The price is speed and fractions whose size can grow quickly, since denominators multiply. A common approach for currency is to store whole cents in an int64 instead; use Rat for things like tax rates and splitting a bill.

big.Float: chosen precision

big.Float is a binary floating-point number whose precision in bits you control (default: 64 for NewFloat, which takes a float64). It can also represent exponents far beyond the range of float64. Set the precision with SetPrec before you compute:

Go Higher precision with big.Float

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The Accuracy value returned by conversion methods tells you whether the result was rounded below, above or exactly (Below, Above, Exact). Text(format, digits) uses the same format letters as strconv.FormatFloat: 'f', 'e', 'g'. Unlike big.Int, a big.Float loses information when precision is too low, so choose it according to the digits you need: roughly 3.32 bits per decimal digit.

Practical advice

  • Allocate with new(big.Int) (or big.NewInt) before calling a method; a nil *big.Int panics.
  • Never copy a big.Int with =. Copying the struct shares the internal slice. Use new(big.Int).Set(x).
  • Compare with Cmp, not ==, which would compare pointers.
  • Don't mix up the receiver and arguments. In z.Sub(x, y), the result is x - y.
  • Use fmt: %v, %d and %s work for *big.Int, *big.Rat and *big.Float (%f, %g and %e for floats).
  • Mind performance. Operations allocate and cost grows with the number of digits. Reuse variables in hot loops, and measure before assuming big is the bottleneck (see Testing for benchmarks).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does z.Add(x, y) do for a *big.Int z?

    big methods write the result into the receiver and return it, which allows chaining and memory reuse.
  2. 2. How should you compare two *big.Int values for equality?

    == compares pointers. Cmp returns -1, 0 or +1, so Cmp(b) == 0 means the values are equal.
  3. 3. Why use big.Rat for 1/10 + 2/10?

    Rat keeps numerator and denominator, so there is no binary rounding error like in float64's 0.1 + 0.2.
  4. 4. What does Exp(x, y, m) with a non-nil m compute?

    Modular exponentiation is the basis of RSA and similar schemes. Passing nil for m gives plain x^y.
  5. 5. Which statement about big.Float is true?

    big.Float is binary floating point with a configurable mantissa precision; it can hold much bigger exponents than float64.

Summary

  • math/big provides big.Int (integers), big.Rat (exact fractions) and big.Float (floating point with configurable precision), all without the fixed limits of built-in types.
  • Methods store the result in the receiver and return it: z.Mul(x, y) means z = x * y; allocate with new or NewInt first.
  • Compare with Cmp, copy with Set, and parse text with SetString.
  • Exp, GCD, ModInverse, Sqrt and ProbablyPrime cover modular arithmetic and primality tests.
  • Rat avoids rounding errors; Float needs SetPrec to choose its precision in bits.
  • Big numbers are slower; use them only when int64 or float64 are not enough.

Next: Packages starts the chapter on modules and packages.