Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 147 ยท Standard Library

Math and Random Numbers

Use Go's math package, understand NaN, Inf and float precision, generate repeatable random numbers with math/rand/v2 (PCG, ChaCha8), pick secure values with crypto/rand and compute simple statistics.

Numbers are everywhere in programs, and Go gives you three groups of tools for them: the math package for mathematical functions and special values, math/rand/v2 for fast pseudo-random numbers, and crypto/rand for random numbers that are safe to use in security-sensitive code. This lesson covers all three, explains the traps that catch beginners (floating-point rounding, NaN, integer overflow, the wrong random package for passwords), and finishes with a few statistics helpers you can write in a handful of lines.

If you need the basics of integer and float types first, read numbers and type conversion. Everything below runs in the editor, and every random example uses a fixed seed so that you get the same output on every run, which is how you should write tests for random code too.

Common math functions

All functions in math work on float64. They return float64 as well, so convert integers explicitly before and after:

Go Roots, powers, rounding and logarithms

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.

Notes on what you just saw:

  • math.Round rounds halves away from zero (2.5 becomes 3, -2.5 becomes -3). math.RoundToEven rounds halves to the nearest even number (2.5 becomes 2), which avoids a statistical bias when you round many values.
  • Floor goes toward negative infinity and Ceil toward positive infinity, so for negative numbers they behave opposite to what many people expect: Floor(-2.5) is -3.
  • Angles are in radians, not degrees. Convert with degrees * math.Pi / 180.
  • int(v) on a float truncates toward zero. It does not round. Note the compile error for constants: int(3.99) with a literal is rejected with cannot convert 3.99 (untyped float constant) to type int, but a variable is fine.
  • The builtin max and min (Go 1.21) work for integers, floats and strings, take any number of arguments, and are usually nicer than math.Max, which only handles floats.

The package also defines constants such as math.Pi, math.E, math.MaxInt64, math.MinInt64, math.MaxInt32, math.MaxUint32, math.MaxFloat64 and math.SmallestNonzeroFloat64. The integer limit constants are untyped, so var x int32 = math.MaxInt32 works, while var x int32 = math.MaxInt64 is a compile error.

Special values: Inf and NaN

Floating-point arithmetic never panics. Dividing a float by zero gives an infinity, and impossible operations give NaN ("not a number"):

Go Infinity, NaN and the trouble with comparing floats

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.

Four lessons hide in that output:

  1. Division by zero for floats gives +Inf, -Inf or NaN. Division by zero for integers is different: it panics at run time (integer divide by zero), and with a constant zero the compiler rejects it.
  2. NaN compares false with everything, including itself. The only reliable test is math.IsNaN(x). This is also why a NaN used as a map key can never be found again.
  3. 0.1 + 0.2 is 0.30000000000000004 with variables, because the nearest float64 values are slightly off. With constants Go does the arithmetic exactly (see constants) and the result equals 0.3. Never compare computed floats with ==; use a tolerance, as in the epsilon line.
  4. A float32 has only about 7 decimal digits of precision. Use float64 unless you have a specific reason.

Never use float64 for money. Store whole cents in an int64 (or use a decimal library) so that additions are exact, and format with fmt.Sprintf("$%d.%02d", cents/100, cents%100).

Integer arithmetic details

Integer math has its own surprises:

Go Integer division, remainders and overflow

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.

-7 / 2 is -3 (not -4), and -7 % 3 is -1. Go always truncates toward zero, so the remainder has the sign of the left operand. If you need an index that wraps around a ring buffer, use (i%n + n) % n, which gives 4 for -1 in a ring of 5.

Integer overflow is silent in Go: int8(127) + 1 is -128. Check before you add when the numbers can come from outside, or use math/bits.Add64, Mul64 and friends, which report the carry.

Pseudo-random numbers with math/rand/v2

The package math/rand/v2 (added in Go 1.22) is the one to use. The old math/rand still exists for compatibility, but v2 has a cleaner API and better generators. Import it with import "math/rand/v2"; the package name in your code is just rand.

There are two ways to use it:

  • Top-level functions such as rand.IntN(10), rand.Float64() or rand.Shuffle(...). They use a global generator that is seeded randomly at startup, so each run differs. They are safe to call from many goroutines. Perfect for things like picking a jitter value or a game's dice roll.
  • Your own generator: rand.New(source). Pick a source, give it a seed, and the sequence is fully repeatable. This is what you want for tests, simulations and reproducible bug reports.

There are two built-in sources: rand.NewPCG(seed1, seed2) (small, fast, good for general use) and rand.NewChaCha8(seed) (takes a 32-byte seed, is much harder to predict, and is the one the global generator uses internally). Neither is safe for concurrent use when you create it yourself: give each goroutine its own generator or protect it with a mutex.

Go Seeded generators give repeatable sequences

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 first and fourth lines are identical because they use the same seed. PCG and ChaCha8 produce the same sequence on every machine and every Go version (the package documents them as stable), so you can safely put expected values in tests.

The main methods

Call Result
r.IntN(n) an int in [0, n); panics if n <= 0
r.Float64() a float64 in [0.0, 1.0)
r.Int64(), r.Uint32(), ... any value of that type
r.Perm(n) a random permutation of 0..n-1
r.Shuffle(n, swap) shuffles anything, using your swap function
r.NormFloat64(), r.ExpFloat64() normal (mean 0, sd 1) and exponential distributions
rand.N(max) generic: a random value of any integer type, including time.Duration, in [0, max)

Two details are worth knowing. Ranges are always half-open: the upper bound is never returned, so a die is r.IntN(6) + 1, and a number in [lo, hi) is lo + r.IntN(hi-lo). And IntN avoids the modulo bias that you get from r.Int() % n, so every value in the range has an equal chance.

Go Dice, shuffling and a generic random duration

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 counts are close to 1000 each but not equal: randomness is not evenness. The jitter line uses the unseeded top-level function, so it prints only a property (true) that holds on every run, never the random value itself.

The old math/rand package needed rand.Seed(time.Now().UnixNano()) to avoid the same sequence on every run. In Go 1.20 and later the global generator is seeded randomly on its own, and in math/rand/v2 there is no Seed function at all. If you see rand.Seed in old code, you can delete it.

Secure random numbers with crypto/rand

Pseudo-random generators are predictable: once someone sees a few outputs, they can often work out the seed and all following values. That is fine for dice and shuffling, and a disaster for session tokens, password reset links, API keys and encryption keys. For those, use crypto/rand, which reads from the operating system's secure random source.

Go Tokens and random numbers from crypto/rand

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 output shows only lengths and booleans, because the real values are different on every run, which is the whole point. rand.Read fills a byte slice, rand.Text() gives you a ready-made token string, and rand.Int picks a uniform integer below a *big.Int limit. Since Go 1.24, rand.Read is guaranteed not to return an error (the program crashes instead if the system's randomness fails), though checking the error is harmless.

The rule is simple: if an attacker guessing the value would hurt you, use crypto/rand. Otherwise math/rand/v2 is faster and fine. Never seed math/rand with the time to "make it secure"; that does not work. The hashing and cryptography lesson goes deeper into safe randomness.

Big numbers: a short recap

When int64 is not enough, the math/big package has big.Int (any size integers), big.Rat (exact fractions) and big.Float (floats with a chosen precision). They are pointer-based, and methods store the result in their receiver:

Go math/big for huge numbers and exact fractions

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.

A big.Rat is the right tool for exact decimal-like calculations such as "a third plus a sixth". Remember that big values are much slower than built-in numbers, so use them only where you need the range or exactness.

Statistical helpers

The standard library has no statistics package, but the common measures are short to write, especially with generics and the slices package (see slices and maps packages):

Go Mean, median, standard deviation and a Monte Carlo estimate

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 data set 2, 4, 4, 4, 5, 5, 7, 9 has a mean of 5 and a population standard deviation of exactly 2, which makes it a favorite for checking your formulas. The estimate of pi uses 200,000 random points: the fraction that lands inside the quarter circle is about pi/4. With a fixed seed the result is always the same; with more trials it gets closer to the true value, but only slowly.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does math.Round(-2.5) return?

    math.Round rounds halves away from zero, so -2.5 becomes -3. math.RoundToEven would give -2.
  2. 2. What does math.NaN() == math.NaN() evaluate to?

    NaN is not equal to anything, including itself. Use math.IsNaN(x) to test for it.
  3. 3. Which package should you use to create a password reset token?

    Tokens must be unpredictable. Only crypto/rand reads from the operating system's secure random source. Pseudo-random generators can be predicted from their output.
  4. 4. Which expression returns a random integer from 1 to 6 inclusive, using a *rand.Rand named r from math/rand/v2?

    IntN(n) returns a value in [0, n), so IntN(6) gives 0 to 5. Adding 1 gives 1 to 6. IntN takes a single argument.
  5. 5. In Go, what is the value of -7 % 3?

    Go truncates integer division toward zero, so -7 / 3 is -2 and the remainder has the sign of the left operand: -7 - (-2 * 3) = -1.

Summary

  • math works on float64: Sqrt, Pow, Floor, Ceil, Round, Trunc, Log, trigonometry (in radians), and constants like math.Pi and math.MaxInt64. The builtin min and max handle any ordered type.
  • Float division by zero gives Inf or NaN; integer division by zero panics. Test NaN with math.IsNaN, and compare floats with a tolerance, not ==.
  • Integer overflow wraps silently, division truncates toward zero, and % takes the sign of the left operand.
  • Use math/rand/v2: top-level functions are randomly seeded, and rand.New(rand.NewPCG(a, b)) or rand.NewChaCha8(seed) give repeatable sequences for tests and simulations. IntN, Float64, Perm, Shuffle and the generic rand.N cover most needs.
  • Use crypto/rand (Read, Text, Int) for anything an attacker must not guess.
  • math/big offers Int, Rat and Float for huge or exact numbers. Never use floats for money.
  • Simple statistics are a few lines with slices; seeded generators make even random simulations testable.

Next: os, io and bufio shows how Go reads and writes data with readers, writers and buffers.