I am attempting to generate a random numbers with a logarithmic distribution.
Where n=1 occurs half of the time, n=2 occurs a aurter of the time, n=3 occurs an eight 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);
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
.
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?
Thanks