USer22999299
USer22999299

Reputation: 5684

How to create a list of 1000 random numbers in Erlang?

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.

Upvotes: 14

Views: 17117

Answers (6)

Farshid Ashouri
Farshid Ashouri

Reputation: 17721

You need to correctly seed first of all.

_ = rand:seed(exs1024s),
[rand:uniform(100) || _ <- lists:seq(1, 1000)].

Upvotes: 0

Adam Lindberg
Adam Lindberg

Reputation: 16587

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.

Upvotes: 26

Ashwin
Ashwin

Reputation: 76

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)).

Upvotes: 1

zie1ony
zie1ony

Reputation: 1260

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)].

Upvotes: 2

Tilman
Tilman

Reputation: 2005

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.

Upvotes: 13

Emil Vikstr&#246;m
Emil Vikstr&#246;m

Reputation: 91983

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.

Upvotes: 2

Related Questions