将[0,1]区间扩展为[a,b]的正确方法是什么?

Geo*_*lly 3 language-agnostic random

许多随机数生成器返回0到1之间的浮点数.

ab之间获得整数的最佳和正确方法是什么?

Dr.*_*ius 5

将区间[0,1]除以B-A + 1区间

实施例A = 2,B = 5

        [----+----+----+----]
        0    1/4  1/2  3/4  1
Maps to    2    3    4    5
Run Code Online (Sandbox Code Playgroud)

公式的问题

 Int (Rnd() * (B-A+1)) + A
Run Code Online (Sandbox Code Playgroud)

是你的Rnd()生成间隔在两侧都是闭合的,因此0和1都是可能的输出,当Rnd()正好为1时,公式给出6.

在实际随机分布(非伪)中,1具有概率零.我认为编程类似于以下内容是安全的:

 r=Rnd()
 if r equal 1
     MyInt = B
 else
     MyInt = Int(r * (B-A+1)) + A
 endif
Run Code Online (Sandbox Code Playgroud)

编辑

只是在Mathematica中进行快速测试:

定义我们的功能:

f[a_, b_] :=  If[(r = RandomReal[]) == 1, b, IntegerPart[r (b - a + 1)] + a]
Run Code Online (Sandbox Code Playgroud)

在[1,100]中构建一个包含3个10 ^ 5个数字的表格:

table = SortBy[Tally[Table[f[1, 100], {300000}]], First]
Run Code Online (Sandbox Code Playgroud)

检查最小值和最大值:

In[137]:= {Max[First /@ table], Min[First /@ table]}

Out[137]= {100, 1}  
Run Code Online (Sandbox Code Playgroud)

让我们看看分布:

BarChart[Last /@ SortBy[Tally[Table[f[1, 100], {300000}]], First],
        ChartStyle -> "DarkRainbow"]  
Run Code Online (Sandbox Code Playgroud)

替代文字