News Archive
PhpRiot Newsletter
Your Email Address:

More information

Monte Carlo Simulations

Note: This article was originally published at Planet PHP on 2 July 2010.
Planet PHP

Monte Carlo simulations are a handy tool for looking at situations that have some aspect of uncertainty, by modelling them with a pseudo-random element and conducting a large number of trials. There isn't a hard and fast Monte Carlo algorithm, but the process generally goes: start with a situation you wish to model, write a program to describe it that includes a random input, run that program many times, and look at the results.

In each case, you're taking a pot shot at the result, and over many iterations you should get a broad picture of the probabilities of certain outcomes. If these match observations of the real situation, your model is a good one. Alternatively, if you can achieve certain results through randomness that others put down to some other factor, perhaps there is more chance in the real situation that others have expected.

As an example, lets imagine visiting an SEO expo, filled with 10,000 SEO experts. Now, 20% of the experts are creative copywriters and link profile experts who will help to make your site more usable, more readable, faster, and help drive traffic from disparate sources as they improve your search profile. The others are clueless keyword stuffers and link spammers, who will turn your site into an real mess.

However, a given rank on a results page is dependent on an awful lot of things - how the site was originally, what other sites are doing, changes to google's algorithms, temporary network and server effects and so on. Because of that, sometimes the bad SEOs get their sites onto the front page, and sometimes the good ones don't. Let estimate that the good SEOs get their site onto the first page under a given term two thirds of the time, while for the bad SEOs it's only one third of the time. Now, whichever SEO you ask claims to be in the good category, of course, so you ask to see the results for the last 5 sites they optimised. If they are all on the first page, can you be confident you've got a good one?

We can set up a monte carlo simulation for that by simply looping over the five sites, and seeing which ones succeed each time, by chance, and which fail. Starting with our total 10,000 SEO population, how many good vs bad SEOs do we expect.

$tGood = $tBad = 0;
$iterations = 10000;

for($iters = 0; $iters $iterations; $iters++) {
A A A A $goodCount = 2000;
A A A A $badCount = 8000;

A A A A for($i = 0; $i 5; $i++) {
A A A A A A A A $max = $goodCount;
A A A A A A A A for($j = 0; $j $max; $j++) {
A A A A A A A A A A A A if(lcg_value() 0.33) {

Truncated by Planet PHP, read more at the original (another 16171 bytes)