^{2}) 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();

}

}

## No comments:

Post a Comment