We will create a Java program tossing a coin simulation and randomize each result with Math.random. After that, we will test convergence of probebilities of heads and tails
Java Program to Toss a Coin
Tossing a coin is a random event and probability is 0.5 for both sides. So lets use Math.random for generating a random number between 0 and 1 and depend on this random value, we will produce a coin value (head or tail).
double rand=Math.random(); String coin=""; if(rand < 0.5) coin="Head"; else coin="Tail"; System.out.println(coin);
This code will produce a single head/tail simulation result. Let's increase the number of attempts and calculate probability of each result.
Example: Tossing a coin 10 times
for (int i=1; i<=10; i++) { double rand=Math.random(); String coin=""; if(rand < 0.5) coin="Head"; else coin="Tail"; System.out.print(coin+" "); //Tail Head Tail Tail Head Tail Head Head Head Tail }
Example: Tossing a coin 10 times and Calculating Probabilities
int head=0, tail=0; for (int i=1; i<=10; i++) { double rand=Math.random(); String coin=""; if(rand < 0.5) head++; else tail++; } System.out.println("Head Probability:"+(head)/10.0); System.out.println("Tail Probability:"+(tail)/10.0);
My Output for 10 attempts:
Head Probability:0.7 Tail Probability:0.3
Example: Tossing a coin 1000 times and Calculating Probabilities
Note: we expect probabilities to converge to 0.5 as the number of attempts increases. For ease of use, let's create a variable ofor number of attempts.
double head=0, tail=0; int numberOfAttempts=1000; for (int i=1; i<=numberOfAttempts; i++) { double rand=Math.random(); String coin=""; if(rand < 0.5) head++; else tail++; } System.out.println("Head Results:"+head); System.out.println("Tail Results:"+tail); System.out.println("Head Probability:"+(head)/numberOfAttempts); System.out.println("Tail Probability:"+(tail)/numberOfAttempts);
My Output:
Head Results:497.0 Tail Results:503.0 Head Probability:0.497 Tail Probability:0.503