我确信有一个功能。我只想列出 1000 个数字,每个数字都应该是随机的。
6 回答
要生成一个包含 1 到 10 之间随机数的 1000 元素列表:
[rand:uniform(10) || _ <- lists:seq(1, 1000)].
将 10 和 1000 更改为适当的数字。如果您从rand:uniform
调用中省略 10,您将得到一个介于 0.0 和 1.0 之间的随机浮点数。
在低于 18.0 的 Erlang 版本上:改用random
模块。警告!您需要random:seed/3
在每个进程使用它之前运行它,以避免获得相同的伪随机数。
确保适当播种。
> 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]
你的直觉是结果会有所不同。Erlang 中的随机种子是特定于进程的。默认种子是固定的。这就是为什么即使示例中有两个进程也会得到相同结果的原因。
> 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]
请注意,如果 的返回值now()
在两个不同的进程中相同,您最终会遇到与上述相同的问题。这就是为什么有些人喜欢使用 agen_server
来包装随机数生成的原因。或者,您可以使用更好的种子。
我会更乐意获得一个我可以在那里阅读的网站。谢谢。
你应该看看Learn You Some Erlang,它将指导你学习这门语言。
来自加密模块的伪随机数生成器效果更好crypto:rand_uniform(From, To)
。
要生成一个包含 1 到 10 之间随机数的 1000 元素列表:
crypto:start(),
[crypto:rand_uniform(1, 10) || _ <- lists:seq(1, 1000)].
来自 Erlang Central wiki:
http://erlangcentral.org/wiki/index.php?title=Random_Numbers
其中 N = 项目数,StartVal = 最小值,Lim = 最大值
generate_random_int_list(N,StartVal,Lim) ->
lists:map(fun (_) -> random:uniform(Lim-StartVal) + StartVal end, lists:seq(1,N)).
您首先需要正确播种。
_ = rand:seed(exs1024s),
[rand:uniform(100) || _ <- lists:seq(1, 1000)].