Happy Pi Day and Monte Carlo Method
Pi Calculation
Today is the
day, 03/14 2010. Happy
day to all!
The Monte Carlo method generates multiple trials to determine the expected value of a random variable.
Calculating Pi is generally the hello world of Monte Carlo Method in Stochastic Calculus. So for today, I will try to give a sample calculation of pi as monte carlo in F#. There are very good articles on the Monte carlo and how the pi calculation is formulated.
Generally these are the steps to follow, before running the simulation
- Define the input set
- Generate randomly the input set
- Filter the random set using some computations
- Fold the result to the final result
Pi calculation formula :

open System let calcPi() = let ran = new Random() let distances = seq { for i in 0 .. 100000 do let x,y = ran.NextDouble(), ran.NextDouble() yield sqrt (x * x + y * y) } let count = distances |> Seq.filter (fun distance -> distance <= 1.0) |> Seq.length 4.0 * (float count) / (float (Seq.length distances)) let errorRate() = (1.0 - (calcPi() / Math.PI)) * 100.0 let print5 value = for i in 0 .. 5 do printf "%f\n" (value()) print5 (errorRate)
val calcPi : unit -> float
val errorRate : unit -> float
val print5 : (unit -> float) -> unit
Error rates:
-0.024698
-0.093453
-0.013239
-0.094726
-0.373563
0.308887
>
.
val errorRate : unit -> float
val print5 : (unit -> float) -> unit
Error rates:
-0.024698
-0.093453
-0.013239
-0.094726
-0.373563
0.308887
>


