Saturday, November 10, 2007

Bernoulli Trials

When you toss a coin, the chances that a head shows are 50/50. But using Bernoulli Trials, we can repeats the coin tosses any number of times to obtain a spread of probabilities - the bell curve we all know. Below is the Java implementation of this idea. The algorithm likely runs in O(n2) time, so it is not efficient for large experiments.


/**
* Prints a histogram showing the results of tossing a coin many times
* and the probability that either heads or tails will be shown. This is
* generally known as the sequence of Bernoulli Trials in probability theory.
* @param trials Number of times to repeat the experiment.
* @param flips Number of coin flips per experiment.
*/
public static void bernoulliTrials(int trials, int flips) {
int i, j, cnt;
int[] f = new int[flips + 1];
for (j = 0; j <= flips; j++)
f[j] = 0;
for (i = 0; i < trials; i++, f[cnt]++)
for (cnt = 0, j = 0; j <= flips; j++)
if (Math.random() < 0.5)
cnt++;
// Drawing the histogram
for (j = 0; j <= flips; j++) {
if (f[j] == 0)
System.out.print(".");
for (i = 0; i < f[j]; i += 10)
System.out.print("*");
System.out.println();
}
}