Reply To: Erlang distributed random numbers

Home Forums Basic Erlang Erlang distributed random numbers Reply To: Erlang distributed random numbers


Tomasz Kowal

Hi mbeddo,

I would do something like this:

%% erlang/2 returns a random number from an Erlang-K distribution
%% with a rate R. K must be a positive integer.
erlang(K, R) when is_integer(K), is_number(R), K > 0, R > 0 ->
     erlang(K, R, 1).

%% erlang/3 are functions that generate Erlang random numbers
%% according to the recipe given in the Wiki article about Erlang
%% distribution.
erlang(0, R, Acc) ->
erlang(K, R, Acc) ->
    erlang(K-1, R, Acc*random:uniform()).

As you can see, I added guards as early as possible in the erlang/2.
When you separate guards with comma, they are treated like logical “AND”,
so all of them have to match.


mymodule:erlang(1, 3.0).


mymodule:erlang(-1, 2).
** exception error: no function clause matching mymodule:erlang(-1,2) (mymodule.erl, line 7)

This is usually enough information for someone to check out the source
and look for the guards expressions.
If you want to give specific error message, like “K should be positive real number”,
you can use case in erlang/2, but I think guards are enough.