Search code examples
javarandomcoin-flipping

Coin toss using random numbers does not appear exactly random


I wanted a random number generator to simulate a coin toss and here's what i did

public class CoinToss
{
    public static void main(String args[])
    {
        int num=(int)(1000*Math.random());
        if(num<500)
            System.out.println("H");
        else
            System.out.println("T");
    }
}

The results were discouraging as i got 16 Heads and 4 tails in 20 runs. That does not appear to be random. Its possible but i want a general opinion if the program is correct ? Am i missing something mathematically ?


Solution

  • Modified your code a little and it seems to be random enough.

    code:

        int h = 0;
        int t = 0;
        for (int i = 0; i < 1000; i++) {
            int num = (int) (1000 * Math.random());
            if (num < 500) {
                h++;
    
            } else {
                t++;
    
            }
        }
        System.out.println("T:" + t);
        System.out.println("H:" + h);
    

    output:

    T:506
    H:494
    

    I guess this is the thing with randomness ^^