Random Numbers

From Erlang Community

(Difference between revisions)
Revision as of 10:32, 25 September 2006 (edit)
Ayrnieu (Talk | contribs)
(they aren't different 'forms' of 'random:uniform', they are two separate functions ; use cleaner password example; remove annoying dict example; minor cleanps)
← Previous diff
Current revision (07:32, 24 March 2009) (edit) (undo)
Wesley (Talk | contribs)
m (random:uniform/1 never returns 0)
 
Line 5: Line 5:
== Solution == == Solution ==
-Use random:uniform/0 and random:uniform/1 ; the first returns a random float uniformly distributed between [0.0,1.1], and the second returns a random integer uniformly distributed between [0,N].+Use random:uniform/0 and random:uniform/1 ; the first returns a random float uniformly distributed between [0.0,1.1], and the second returns a random integer uniformly distributed between [1,N].
<code> <code>
1> random:uniform(). 1> random:uniform().

Current revision

[edit] Problem

You want a random number from a given range. For example, you wish to randomly select one element from an array, simulate rolling a die in a game of chance, or generate a random password.

[edit] Solution

Use random:uniform/0 and random:uniform/1 ; the first returns a random float uniformly distributed between [0.0,1.1], and the second returns a random integer uniformly distributed between [1,N].

1> random:uniform().
0.159112
2> random:uniform(150).
67

To select random integers from [N,M], can use N+random:uniform(M-N).

A common example is generating a random password:

generate_password(N) ->
    lists:map(fun (_) -> random:uniform(90)+$\s+1 end, lists:seq(1,N)).

3> generate_password(8).
"l?8j#$&&"
4> generate_password(8).
"V generate_password(8).
"irp^DXTz"

The Erlang random number generator is attributed to B.A. Wichmann and I.D.Hill, in 'An efficient and portable pseudo-random number generator', Journal of Applied Statistics. AS183. 1982. Also Byte March 1987.

It can support bigint values, so no special recipe is required for extremely large random numbers.

Erlang/OTP Projects
Personal tools