Java:生成具有对数分布的随机数 [英] Java: Generating a random numbers with a logarithmic distribution
问题描述
我正在尝试生成具有对数分布的随机数.
I am attempting to generate a random numbers with a logarithmic distribution.
n = 1出现在一半时间,n = 2出现在四分之一的时间,n = 3出现在八分之一的时间等的情况.
Where n=1 occurs half of the time, n=2 occurs a quarter of the time, n=3 occurs an eighth of the time, etc.
int maxN = 5;
int t = 1 << (maxN); // 2^maxN
int n = maxN -
((int) (Math.log((Math.random() * t))
/ Math.log(2))); // maxN - log2(1..maxN)
System.out.println("n=" + n);
在大多数情况下,我会得到所需的结果,但是每隔一段时间,我会得到一个比maxN
大的n
值.
Most of the time, I am getting the result I need, however once every so often, I get a value of n
that is larger than maxN
.
为什么会这样?我的看法是,Math.random()
的最大值是1.0;
因此(Math.random() * t))
的最大值为t
;
由于t = 2 ^ maxN,因此log2(t)的最大值为maxN;
Why is this so? The way I see it, the max value of Math.random()
is 1.0;
therefore the max value of (Math.random() * t))
is t
;
therefore the max value of log2(t) is maxN, since t = 2^maxN;
我的逻辑在哪里偏离了轨道?
Where has my logic gone off track?
谢谢
推荐答案
小于1.0的对数为负.当生成的随机数小于1.0时,表达式((int) (Math.log(Math.random() * t) / Math.log(2)))
为负数,因此maxN - (the negative number)
大于maxN.
logarithm of numbers less than 1.0 is negative. When the random number generated is such that it is less than 1.0, the expression ((int) (Math.log(Math.random() * t) / Math.log(2)))
is a negative number and hence maxN - (the negative number)
is more than maxN.
下面的表达式应该给出正确的分布.
The following expression should give correct distribution.
n = Math.floor(Math.log((Math.random() * t) + 1)/Math.log(2))
请注意:
0.0 <= Math.random() <= 1.0
0.0 <= Math.random() * t <= t
1.0 <= (Math.random() * t) + 1 <= t + 1.0
0.0 <= Math.log((Math.random() * t) + 1) <= Math.log(t + 1.0)
0.0 <= Math.log((Math.random() * t) + 1)/Math.log(2) <= Math.log(t + 1.0)/Math.log(2)
Since t = 2^maxN,
Math.log(t + 1.0)/Math.log(2) is slightly larger than maxN.
So do a Math.floor and you get the correct result:
0.0 <= Math.floor(Math.log((Math.random() * t) + 1)/Math.log(2)) <= maxN
这篇关于Java:生成具有对数分布的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!