问题描述
许多随机数生成器返回0到1之间的浮点数.
Many random-number generators return floating numbers between 0 and 1.
在 a 和 b 之间获得 integers 的最佳和正确方法是什么?
What's the best and correct way to get integers between a and b?
推荐答案
将间隔[0,1]划分为B-A + 1个单元格
Divide the interval [0,1] in B-A+1 bins
示例A = 2,B = 5
Example A=2, B=5
[----+----+----+----]
0 1/4 1/2 3/4 1
Maps to 2 3 4 5
公式问题
Int (Rnd() * (B-A+1)) + A
您的Rnd()生成间隔在两侧都是闭合的,因此0和1都是可能的输出,并且当Rnd()恰好为1时,公式给出6.
is that your Rnd() generation interval is closed on both sides, thus the 0 and the 1 are both possible outputs and the formula gives 6 when the Rnd() is exactly 1.
在实际的随机分布(不是伪)中,1的概率为零.我认为对类似这样的程序进行编程是足够安全的:
In a real random distribution (not pseudo), the 1 has probability zero. I think it is safe enough to program something like:
r=Rnd()
if r equal 1
MyInt = B
else
MyInt = Int(r * (B-A+1)) + A
endif
修改
在 Mathematica 中进行快速测试:
定义我们的功能:
f[a_, b_] := If[(r = RandomReal[]) == 1, b, IntegerPart[r (b - a + 1)] + a]
用[1,100]中的3个10 ^ 5数字构建表格:
Build a table with 3 10^5 numbers in [1,100]:
table = SortBy[Tally[Table[f[1, 100], {300000}]], First]
检查最小和最大:
In[137]:= {Max[First /@ table], Min[First /@ table]}
Out[137]= {100, 1}
让我们看看分布:
BarChart[Last /@ SortBy[Tally[Table[f[1, 100], {300000}]], First],
ChartStyle -> "DarkRainbow"]
这篇关于将[0,1]间隔扩展为[a,b]的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!