## Sunday, June 08, 2008

### Using a Random Number Generator to estimate e

After this post I started to wonder what other constants can be estimated using probabalistic methods.

You can estimate e = 2.7182818 using
monte carlo methods. The sum S = X1 + X2 + ... + Xn > 1 averages as the eth element. So if you rand(0,1)+rand(0,1)+... until they are greater then 1. If you average the number of elements needed it approximates e.

This code is dog ugly and probably bug riddled but it might give you some idea how the calculation is done.
`i=0N=1000000number=0total=0  p=0k=1   while k < N        i=i+rand    p=p+1  if i>1     total=total+p     number=number+1     p=0     i=0  end      k=k+1   end   total=total.quo(number)   puts "e is #{total}"`

If you know of a better way to use iterators to carry out this calculation please comment.

#### 4 comments:

sjs said...
This comment has been removed by the author.
sjs said...

I think some of your code was eaten. That should probably be: while k < N, then a few missing lines.

manveru said...
This comment has been removed by the author.
manveru said...

Maybe something like in this paste