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=0
N=1000000
number=0
total=0
p=0
k=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.
This comment has been removed by the author.
ReplyDeleteI think some of your code was eaten. That should probably be: while k < N, then a few missing lines.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteMaybe something like in this paste
ReplyDelete