java - Simulate the tossing of a coin three times and print out the percentage of cases in which one gets three tails -
attached problem: http://puu.sh/42qti/ea955e5bef.png
in terms of code, have far
the question asks "calculate simulated percentage of 3 tails," part stuck on. give me insight on progress next?
public static boolean isthreetails(){ random rand = new random(); int numberoftosses = 3; int numberofheads = 0; int numberoftails = 0; for(int = 1; <= numberoftosses; i++){ int value = rand.nextint(2); if(value == 0){ numberoftails++; }else{ numberofheads++; } } if(numberoftails == 3){ return true; } else{ return false; } } double numtosses = 1000000; //choose whatever here double threetails = 0; for(int =0; < numtosses; i++){ if(isthreetails()){ threetails++; } } system.out.println("theoretical probability of 3 tails: " + (double) 1/8); system.out.println("actual results " + numtosses + " tosses = " + threetails/numtosses);
edit: here, creating counter when there triple tails. increment numberoftripletails
counter. if rolls "h", numberoftails
go zero. however, code seems give '3' answer.
edit 2: done!
the method have written simulates 3 tosses. i've modified method callable function isthreetails()
public static boolean isthreetails(){ random rand = new random(); int numberoftosses = 3; int numberofheads = 0; int numberoftails = 0; for(int = 1; <= numberoftosses; i++){ int value = rand.nextint(2); if(value == 0){ numberoftails++; }else{ numberofheads++; } } if(numberoftails == 3){ return true; } else{ return false; } }
now want call method main method of threetosses.java
double numtosses = 100; //choose whatever here double threetails = 0; for(int =0; < numtosses; i++){ if(isthreetails()){ threetails++; } } system.out.println("theoretical probability of 3 tails: " + (double) 1/8); system.out.println("actual results " + numtosses + " tosses = " + threetails/numtosses);
Comments
Post a Comment