SoFunction
Updated on 2025-04-08

3 ways to generate random numbers in Erlang

erlang has three ways to produce random numbers

random:uniform().

This function is provided by the erlang library random module. This is generally used.

Copy the codeThe code is as follows:

1> random:uniform().
0.4435846174457203

erlang:now().

I believe many people have done it using the current time as a random time. So if you don’t have too many requirements, of course you can do this.

Copy the codeThe code is as follows:

1> erlang:now().
{1419,831449,715000}

crypto:strong_rand_bytes(N).

The crypto module is a module for encryption. The strong_rand_bytes function can generate uniform random numbers of N bytes. Returns binary data. like

Copy the codeThe code is as follows:

1> <<A:32,B:32,C:32>> = crypto:strong_rand_bytes(12).
<<154,106,144,218,65,238,246,170,246,70,252,167>>
2> A.
2590675162

You can shengcheng, 3 32-bit random numbers, equivalent to 3 random integers.