Home Blog

Generating random numbers

by Michael Banzon <michael@banzon.dk> on 2017-02-06

Let's go crazy and generate some random numbers!

But are they truly random? And why are we generating them?!

Why?

Why do we want to make random numbers?

First we needs to understand that computers can not make truly random numbers. Instead they can generate pseudo-random numbers using an algorithm - which is often based on a starting value called the seed.

In computer science there are (at least) three big areas where random numbers are useful:

How?

In many programming languages it is very trivial to generate a pseudo-random number.

Usually the number will be a floating point value between 0 and 1 - and to get a value in the interval we need to use this as a factor for the interval we want numbers in (pseudo-code):

min_value + (random() * (max_value - min_value))

We'll start by making a small example program (in Go) that simulate a roll with a D6 (six-sided die):

package main

import "fmt"
import "math/rand"

const sides = 6

func main() {
	fmt.Println(rand.Intn(sides) + 1)
}

Check out the example on the Go playground - or on your own computer - it generates the same number every time!

It is because of the seed! Every time it is run it uses the same seed value. To generate another number - or even another sequence of numbers - we need to feed the algorithm a unique seed value. If it is fed the same value it will produce the same sequence of random numbers.

The following example have the changes needed to generate a unique sequence using the current timestamp in nano seconds as the seed (you can run this on the Go playground as well, but it will produce the same sequence every time, as the time used there is fixed):

package main

import "fmt"
import "math/rand"
import "time"

const sides = 6

func main() {
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < 100; i++ {
		fmt.Println(rand.Intn(sides) + 1)
	}
}

Is it random?

I've run a program that made random numbers between 1 and 6 - over two billion times! The result are output every 1.000.000 iterations by counting the occurences for each possible number.

The following graph shows the distribution progression:

Random number distribution progression

As the graph shows the start is a bit rough but the distribution progress towards perfect 1/6.

This does not really show how random the numbers are.

In the previous examples we've seen that using the same seed again will produce the exact same sequence of random numbers - this in itself should be proof they are in fact not really random.

But it's good enough for most applications - such as computer games.

The examples shown/described here is in the companion repository on GitHub along with the sample output data - over two billion iterations each, run 10 times.

RSS Feed