Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 240
USer22999299 Avatar asked Apr 25 '12 14:04

USer22999299


People also ask

How do you generate a random number list?

We can use the above randint() method along with a for loop to generate a list of numbers. We first create an empty list and then append the random numbers generated to the empty list one by one.

What is the best random number algorithm?

You can think of the seed as a snippet of randomness. However, the Mersenne Twister has since replaced linear congruential generators and is still the most popular PRNG algorithm used today. While pseudorandom numbers aren't random in truth, there are many reasons why they're used.

What is rand ()/ Rand_max in C?

C library function - rand() The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.


2 Answers

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.

like image 200
Adam Lindberg Avatar answered Sep 19 '22 11:09

Adam Lindberg


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.

like image 41
Tilman Avatar answered Sep 19 '22 11:09

Tilman