Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you generate a random number in between 1 and 7 by using a function which generates 1 to 5 [duplicate]

Possible Duplicate:
Expand a random range from 1-5 to 1-7

I understood the solution using rejection sampling i.e

public static int rand7() {
    while (true) {
       int num = 5 * (rand5() - 1) + (rand5() - 1);
       if (num < 21) return (num % 7 + 1);
    }
}

but I am thinking of another solution, i.e rand5() is called 7 times and result is divided by 5, but I am not sure whether this is correct. Please let me know if is or isn't.

public static int rand7() {    
    int num = rand5()+rand5()+rand5()+rand5()+rand5()+rand5()+rand5();
    return num/5;
}

EDIT: It looks like the probability of generating 1 is (1/5)^7 but to generate 2 it is 7*(1/5)^7. It is uneven so it is not going to work.

like image 259
hareendra reddy Avatar asked Aug 06 '11 13:08

hareendra reddy


1 Answers

It will not be a uniform distribution (looks normal). And as Paul says, the proof follows from the Central Limit Theorem.

enter image description here

like image 74
Jacob Avatar answered Nov 15 '22 08:11

Jacob