Erlang:关于分布,有没有更好的方法来得到特定范围内的随机整数

ds97pgxw  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(188)

My approach is the following:
Num 1 and Num 2 are given numbers that the beginning and end of the range, the resulting random integer can be num 1 or num 2.

Num1 + rand:uniform(Num2-Num1).

Example:
Num 1 = 3 Num 2 = 20
rand:uniform returns a value between 1 and 17. I then add the Num 1 again, so the random value is in the given range.
I see the problem with this implementation is the distribution of my random numbers, because the lowest number in the range has a higher probability, depending on the distance between 0 and num 1 and the range between num 1 and num 2.
I would appreciate a simpler, more elegant solution that distributes the integers uniformly...

gkl3eglg

gkl3eglg1#

由于rand:uniform(17)返回1到17之间(包括1和17)的数字,因此将其加上3将给予4到20之间的数字。请尝试以下方法:

rand:uniform(Num2 - Num1 + 1) + Num1 - 1

如果Num1为3,Num2为20,则rand:uniform(18) + 2将变为rand:uniform(18) + 2,给出一个介于3和20之间的随机数。

相关问题