Category Archives: F#

Central_limit_theorem.fsx

CLT// an F# script
// inspired by a clojure talk on
// http://gorilla-repl.org/
//https://en.wikipedia.org/wiki/Central_limit_theorem
open System
let rnd = new Random()
let avgrand n = 
    let mutable total = 0.0
    for i = 1 to n do
        total  avgrand m)
let nsamples = 1000
let nrands = 100
let rands = randoms nsamples nrands
//https://www.mathsisfun.com/data/standard-deviation.html
let randcount = float rands.Length
let rmean = Array.sum rands / randcount
let rvariance = (rands |> Array.sumBy (fun r -> (rmean - r) ** 2.0)) / randcount 
let rstddev = sqrt(rvariance) 
let rstdnormal = rands |> Array.map (fun r -> (r - rmean) / rstddev)

let rhist =
    let h = Array.groupBy (fun r -> round(r * 10.0) * 0.1) rstdnormal
    let h2 = h |> Array.map (fun (i,a) -> i,float a.Length * 10.0 / float nsamples)
    h2

//http://mathworld.wolfram.com/StandardNormalDistribution.html
let prob x = 1.0/sqrt(2.0*System.Math.PI)*exp(-x*x/2.0)
let stdnorm = [|for x in -4.0..0.01..4.0 -> x,prob x|]

#r @"C:\Program Files\BayardRock\IFSharp\FSharp.Charting.dll"
#r @"System.Windows.Forms.DataVisualization.dll"
open FSharp.Charting
open FSharp.Charting.ChartTypes
open System.Windows.Forms
open System.Windows.Forms.DataVisualization
let chrt = Chart.Combine( [| Chart.Column(rhist, Name=sprintf "histogram (#samples=%d #randoms=%d)" nsamples nrands)
                             Chart.Line(stdnorm, "standard normal curve") |] )
        |> Chart.WithLegend()
let cc = new ChartTypes.ChartControl(chrt, Dock = DockStyle.Fill)
let form = new Form(Visible = false, TopMost = true, Width = 700, Height = 500)
form.Controls.Add(cc)
form.ShowDialog()
Advertisements