The first method is OK.
The second repeats constantly the same pair of numbers.
It is quite obscure to me why… Could you point to the good direction ?
module Normal =
let rnd = new MersenneTwister()
let sampleNormal =
fun () -> let rec randomNormal() = let u1, u2 = rnd.NextDouble(),rnd.NextDouble()
let r, theta= sqrt (-2. * (log u1)), 2. * System.Math.PI * u2
seq { yield r * sin theta; yield r * cos theta ; printfn "next";yield! randomNormal() }
randomNormal()
let sampleNormalBAD =
fun () -> let rec randomNormal = let u1, u2 = rnd.NextDouble(),rnd.NextDouble()
let r, theta= sqrt (-2. * (log u1)), 2. * System.Math.PI * u2
seq { yield r * sin theta; yield r * cos theta ; printfn "next";yield! randomNormal }
randomNormal
Normal.sampleNormal() |> Seq.take(10) |>Seq.toArray
Normal.sampleNormalBAD() |> Seq.take(10) |>Seq.toArray
In the first sample
randomNormal()is a function, it takes()and return a value, it will be evaluated each time.In the second one
randomNormalis a value, so it will not be evaluated twice, once bounded it will remain with the same value.If you rollover
randomNormal()the signature is :and for
randomNormalis just :UPDATE: It keeps printing because the
printfnis inside the sequence, which is the bounded value.If you try printing in the body before the last line you will see the difference. Here’s a simplified sample code: