Pages

Sunday, January 08, 2012

How to Simulate a Coin Toss in Java


  To simulate a coin toss (we'll do the dice next [Dice Simulation]) we need only two cases: tails or heads. Printing out "tails" or "heads" can represent out outcome, like so:
Case 1: System.out.println("Tails");
Case 2: System.out.println("Heads");

  After establishing our two cases (outcomes) we must have some function act as our flipper (to simulate randomness). Luckily, Java already has one for you and I will show you how to use it:
double randNumber = Math.random();

  Math.random() is a function that is part of the Math class that is incorporated into Java already (for your convenience). Math.random() creates a double (a number that has decimal places), as opposed to an integer which does not have decimal places, in the range approximately of .0000001 to .9999999. Knowing that our function is going to generate a random number between 0 and 1 we can use the following condition to determine which output case to print out to the console.
double randNumber = Math.random();
 if(randNumber>.500){
     System.out.println("Tails"); //case 1
 } else {
     System.out.println("Heads"); //case 2
 }

FEEL FREE TO COPY MY CODE :)

2 comments: