How to create a list of 1000 random numbers in Erl

2020-02-10 17:51发布

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.

6条回答
对你真心纯属浪费
2楼-- · 2020-02-10 17:57

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)].
查看更多
对你真心纯属浪费
3楼-- · 2020-02-10 18:02

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.

查看更多
ゆ 、 Hurt°
4楼-- · 2020-02-10 18:04

You need to correctly seed first of all.

_ = rand:seed(exs1024s),
[rand:uniform(100) || _ <- lists:seq(1, 1000)].
查看更多
Bombasti
5楼-- · 2020-02-10 18:09

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.

查看更多
We Are One
6楼-- · 2020-02-10 18:10

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.

查看更多
【Aperson】
7楼-- · 2020-02-10 18:14

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)).
查看更多
登录 后发表回答