Question

I'm sure that there is a function for that. I just want to make a list of 1000 numbers, each one of them which should be random.

Was it helpful?

Solution

To generate a 1000-element list with random numbers between 1 and 10:

[rand:uniform(10) || _ <- lists:seq(1, 1000)].

Change 10 and 1000 to appropriate numbers. If you omit the 10 from from the rand:uniform call, you'll get a random floating point number between 0.0 and 1.0.

On Erlang versions below 18.0: Use the random module instead. Caution! You need to run random:seed/3 before using it per process, to avoid getting the same pseudo random numbers.

OTHER TIPS

Make sure to seed appropriately.

 > F = fun() -> io:format("~p~n", [[random:uniform(10) || _ <- lists:seq(1, 10)]]) end.
 > spawn(F).
 [1,5,8,10,6,4,6,10,7,5] 
 > spawn(F).
 [1,5,8,10,6,4,6,10,7,5]

Your intuition is that the results would be different. A random seed in Erlang is process specific. The default seed is fixed though. That's why you get the same result even though there are two processes in the example.

 > G = fun() -> {A1,A2,A3} = now(), 
              random:seed(A1, A2, A3), 
              io:format("~p~n", [[random:uniform(10) || _ <- lists:seq(1, 10)]]) 
       end.
 > spawn(G).
 [3,1,10,7,9,4,9,2,8,3]
 > spawn(G).
 [9,1,4,7,8,8,8,3,5,6]

Note that if the return value of now() is the same in two different processes you end up with the same problem as above. Which is why some people like to use a gen_server for wrapping random number generation. Alternatively you can use better seeds.

i will be more then happy to get also a site that i will be able to read it there. thanks.

You should check out Learn You Some Erlang which will guide you through the language.

Pseudorandom number generator from crypto module works better crypto:rand_uniform(From, To).
To generate a 1000-element list with random numbers between 1 and 10:

crypto:start(),
[crypto:rand_uniform(1, 10) || _ <- lists:seq(1, 1000)].

From Erlang Central wiki:

http://erlangcentral.org/wiki/index.php?title=Random_Numbers

Where N = no of items, StartVal = minimum value and Lim = maximum value

generate_random_int_list(N,StartVal,Lim) ->
    lists:map(fun (_) -> random:uniform(Lim-StartVal) + StartVal end, lists:seq(1,N)).

You need to correctly seed first of all.

_ = rand:seed(exs1024s),
[rand:uniform(100) || _ <- lists:seq(1, 1000)].
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top