Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 科尔曼练习:随机(a,b)_Algorithm_Random - Fatal编程技术网

Algorithm 科尔曼练习:随机(a,b)

Algorithm 科尔曼练习:随机(a,b),algorithm,random,Algorithm,Random,我不明白这个练习的答案,尤其是他们为什么要这么做 n = [log(b - a +1 )] ?!! 我认为n=ceil(log2(b)) 以下是练习: 描述一个只调用RANDOM(0,1)的RANDOM(a,b)实现 答案是: 1: n = [lg(b − a + 1)] 2: Initialize an array A of length n 3: while true do 4: for i = 1 to n do 5: A[i] = RANDOM(0, 1) 6:

我不明白这个练习的答案,尤其是他们为什么要这么做

n = [log(b - a +1 )] ?!! 
我认为
n=ceil(log2(b))


以下是练习:

描述一个只调用RANDOM(0,1)RANDOM(a,b)实现

答案是:

1: n = [lg(b − a + 1)] 
2: Initialize an array A of length n
3: while true do
4:    for i = 1 to n do
5:       A[i] = RANDOM(0, 1)
6:    end for
7:    if A holds the binary representation of one of the numbers in a through
b     then
8:          return number represented by A
9:    end if
10: end while

页面链接:

它返回到十进制方法。当您想将一个数字从
(0,1)
映射到
(a,b)
,只需将
(b-a)
中的数字相乘,然后加上
a
。这意味着如果我们在
(a,b)
中有一个数字
x
,我们将有
(b-a)*x+a
,它将
0
映射到
a
1
映射到
b


由于加号
a
是所有数字的线性移位,因此此处忽略此移位。因此,最大的值是
b-a
,而
[a,b]
的紧密集合之间的值的数量是
b-a+1

谢谢你的回答,我认为最大的值是b,在这种情况下,我们需要log2(b)位来编码十进制value@AzizChafik如果它对你有效,你可以接受它作为你问题的答案。