What is best way to create random numbers for dice roller?

I highly recommend using :rand instead of :crypto.

You aren’t aiming to make the next number unpredictable (this is what :crypto is built for), you’re aiming to make the dice be fair; 1/n even chance for each face.

You’ll have a hard enough time convincing your players that the computer dice aren’t rigged without also having to admit “I wrote my own random number generator”.

For example, the trunc approach suggested above has an unexpected bug in it (even after an edit) and will slightly favor 1, 3 and 5 over 2, 4 and 6:

faces = 6
0..255
|> Enum.map(fn x -> trunc(x * faces / 255) + 1 end)
|> Enum.frequencies()

%{1 => 43, 2 => 42, 3 => 43, 4 => 42, 5 => 43, 6 => 42, 7 => 1}

I show this out in detail because I too have gone down this path of ‘I’m going to roll my own RNG that’s using strong crypto’ when I should have just trusted non-crypto-strength randomness for games.

tl;dr Use :rand.uniform(sides) not :crypto.

7 Likes