The Monte Carlo method is to use the mean of a large number of experiments with known probability distribution to estimate some quantity. It is based on the assumption that if you do a lot of trials then your average value should be close to the mean or expectation of that probability distribution.
@dhayden's link is excellent, but I've just spent over an hour failing to prove the relevant theorem, so I'll just have to accept the end result.
Your "experiment" here is conceptually simple: just add up successive values of a variable uniformly distributed on [0,1] and return the number of them when their sum first exceeds 1.0. The theoretical average of the probability distribution is (apparently) e, so your average over a large number of experiments should approach this.
My suggestion:
- have a
double myRand()
function to return a single value uniformly distributed on [0,1]. You can borrow some ideas from
http://www.cplusplus.com/reference/random/uniform_real_distribution/
- have an
int experiment()
function to carry out the simulated experiment and return the number of variables when their sum first exceeds 1.
-
int main()
will then average the result of however many experiments you want.
Although I couldn't prove the result (I'm gutted!) it certainly works:
Trials Estimate
1 2
10 3.2
100 2.54
1000 2.723
10000 2.7465
100000 2.71662
1000000 2.718129
10000000 2.7188502
Actual value of e is 2.7182818 |
More web links at
https://en.wikipedia.org/wiki/E_(mathematical_constant) - see: stochastic representations, near the bottom
http://wiki.stat.ucla.edu/socr/index.php/SOCR_EduMaterials_Activities_LawOfLargeNumbers#Estimating_e_using_SOCR_simulation