java - Random number generation algorithm -
i encountered naive algorithm random number generation produce series of numbers follows:
for (int = 0; < max; i++) if (rand.nextint(100) >= 100 - probability) // probability between 0 , 100 randomnumberslist.add(i); i wondering if there's way achieve statistically equivalent results without iterating through each number between 0 , max.
let's denote p=probability/100 , q=1-p.
consider first number added. probability q 0; probability (1-q)*q 1, probability (1-q)^2*q 2 , on. geometric distribution. can generate random number distributed according geometric distribution using following approach: generate random number u uniformly distributed in [0,1] , calculate x=⌊ln(u)/ln(q)⌋ — x have geometric distribution (see this question).
so how can calculate first number add.
now consider difference between second , first numbers. distributed geometrically (only starting @ 1, not @ 0), can calculate difference same way , obtain second number, , on.
a pseudocode like
cur = -1 lnq = ln(q) while true u = random(0,1) // float! cur = cur + 1 + floor(ln(u)/lnq) if cur >= max break randomnumberslist.add(cur); corresponding java code @traveh
list<integer> randomnumberslist = new linkedlist<integer>(); int cur = -1; double p = probability / 100; double q = 1 - p; double lnq = math.log(q); random random = new random(); while (true) { double u = random.nextdouble(); cur = cur + 1 + (int)math.floor(math.log(u) / lnq); if (cur >= max) break; randomnumberslist.add(cur); }
Comments
Post a Comment