5 people like it.

Calculate PI using Monte Carlo

Estimate the value of PI using a Monte Carlo simulation.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
open Fmat.Numerics
open Fmat.Numerics.MatrixFunctions
open Fmat.Numerics.BasicStat

let calcPi n =
    let x = rand [1;n]
    let y = rand [1;n]
    let d = x .* x + y .* y
    let circ = new Matrix(d .< 1.0)
    let m = sum(circ,1)
    float(m)/(float)n*4.0

let pi = calcPi 4000000
namespace Fmat
namespace Fmat.Numerics
module MatrixFunctions

from Fmat.Numerics
module BasicStat

from Fmat.Numerics
val calcPi : n:int -> float

Full name: Script.calcPi
val n : int
val x : Matrix<float,FloatLib>
val rand : size:seq<int> -> Matrix<float,FloatLib>

Full name: Fmat.Numerics.BasicStat.rand
val y : Matrix<float,FloatLib>
val d : Matrix<float,FloatLib>
val circ : Matrix
Multiple items
type Matrix = Matrix<float,FloatLib>

Full name: Fmat.Numerics.Matrix

--------------------
new : data:'T [,] -> Matrix<'T,'S>
   (+0 other overloads)
new : data:'T [,,] -> Matrix<'T,'S>
   (+0 other overloads)
new : data:'T [,,,] -> Matrix<'T,'S>
   (+0 other overloads)
new : data:seq<'T> -> Matrix<'T,'S>
   (+0 other overloads)
new : data:seq<'T list> -> Matrix<'T,'S>
   (+0 other overloads)
new : data:seq<seq<'T>> -> Matrix<'T,'S>
   (+0 other overloads)
new : data:seq<'T []> -> Matrix<'T,'S>
   (+0 other overloads)
new : data:'T -> Matrix<'T,'S>
   (+0 other overloads)
new : boolMatrix:__BoolMatrix -> Matrix<'T,'S>
   (+0 other overloads)
new : size:seq<int> * data:matrixData<'T> -> Matrix<'T,'S>
   (+0 other overloads)
val m : Matrix<float,FloatLib>
val sum : matrix:Matrix<float,FloatLib> * dim:int -> Matrix<float,FloatLib>

Full name: Fmat.Numerics.BasicStat.sum
Multiple items
val float : value:'T -> float (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.float

--------------------
type float = System.Double

Full name: Microsoft.FSharp.Core.float

--------------------
type float<'Measure> = float

Full name: Microsoft.FSharp.Core.float<_>
val pi : float

Full name: Script.pi
Raw view New version

More information

Link:http://fssnip.net/h2
Posted:4 years ago
Author:Phillip Trelford
Tags: monte carlo , simulation , math , pi