Happy Pi Day and Monte Carlo Method

Pi Calculation

Today is the [math]\pi[/math] day, 03/14 2010. Happy [math]\pi[/math]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

  1. Define the input set

  2. Generate randomly the input set

  3. Filter the random set using some computations

  4. Fold the result to the final result

Pi calculation formula : [math]\frac{Hitting inside the circle} {Hitting Outside the circle} = \frac { 1/4 \pi r^2} { r^2} = \frac {1}{4}\pi[/math]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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

http://www.codingday.com;//downloads/pi.fs;Pi Calculation;.