In this assignment you will simulate the experiment described in hw1 problem # 5, which says: Alice and Bob have 2 + 1 coins, each with probability of a head equal to 1/2. Bob tosses + 1 coins, while Alice tosses the remaining n coins. Show that the probability that after all the coins have been tossed, Bob will have gotten more heads than Alice is 1/2. Write a program, in any language, that runs this experiment with equal to 5, 10, 50 and 100, respectively. For each value of , do 1000 trials, and compute the relative frequency of Bob tossing more heads than Alice. relative frequency = number of trials in which Bob tossed more heads total number of trials Verify that your relative frequency is very close to 0.5, independent of the value of . Now suppose that we do the same sequence of experiments for ∈ {5, 10, 50,100}, with 2 + 1 loaded coins. Suppose the probability of heads is equal to , for ∈ {0.2, 0.3, 0.4, 0.6, 0.7, 0.8}. This should be possible by editing just a few lines of code (replacing 1/2 by a variable which you initialize at the beginning of the program.) Does the probability that Bob tosses more heads than Alice now seem to depend on ? Does that probability seem to approach a limiting value as becomes large? Form a conjecture regarding this probability.
this is the assignment I am supposed to do. Here is my code. I am going to switch the probability and run it again. Here is my code. I am not sure exactly why I keep getting a relativeFreq close to 0. Here is my code
//1. create file
//2. create file writer class
//3. create print writer class
File Report = new File("Report.txt");
FileWriter fw = new FileWriter(Report);
PrintWriter pw = new PrintWriter(fw);
Random rand = new Random(); //randomly flips head or tails
int n[] = new int[4]; // number of coin flips
n[0] = 5;
n[1] = 10;
n[2] = 50;
n[3] = 100;
double p = 5; //prob of 0.2, 0.3, 0.4, 0.6, 0.7, 0.8
int trials = 1000;
int BHC = 0, AHC = 0; // count how many heads bob and alice flipped
int c = 0;
int count = 0;
for(int k = 0; k < n.length; k++) {
while (c < trials) {
//bob: loop n+1 times
for(int i = 0; i < n[k] + 1; i++) {
//get randomNum btwn 0-9
int randomNum = rand.nextInt(10);
//if randomNum is 0 or 1, then Bob flipped head (0.2 prob)
if (randomNum < p)
BHC++;
}
//alice: loop n times
for (int j = 0; j < n[k]; j++) {
//get randomNum btwn 0-9
int randomNum = rand.nextInt(10);
//if randomNum is 0 or 1, then Bob flipped head (0.2 prob)
if (randomNum < p)
AHC++;
}
if (BHC > AHC)
count++;
c++;
}
double relativeFreq = (double)count/(double)trials;
pw.println("The Relative Frequency when n = " + n[k] + " and p = " + p/10 + " is " + relativeFreq);
}
pw.close(); //close file
I believe your issue is that you set BHC and AHC once, before any loops start.
It should be inside the
while(c < trials)loop, so that the flip counts are reset at the start of each test.Also, I think that count = 0 and c = 0 need to be inside the for loop.
Like so: