tried to get my head around sequences and wrote a small example to teach myself

Looks like you have your head around Seq pretty well!

One of the nicer things about F# and other ML derived languages is the ability of the compiler to infer types based use. Therefore, almost all of the type declarations can be removed:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#light

let geometric_brownian_increment_func vol rate incr  =
    (* precompute the drift coefficient *)
    let drift_term = (rate - vol*vol/2.0)*incr
    fun last_pos normrand ->
        last_pos*exp (drift_term + vol*normrand)

let normal_rand_gen (randgen:System.Random) =
    let box_muller =
        let mutable sum_sqrd = 0.0
        let mutable x = 0.0
        let mutable y = 0.0
        let next() = 2.0*randgen.NextDouble() - 1.0
        while sum_sqrd >= 1.0 || sum_sqrd = 0.0 do
            x <- next()
            y <- next()
            sum_sqrd <- x*x + y*y
        x*(sqrt (-2.0*(log sum_sqrd)/sum_sqrd))
    
    fun i -> box_muller

let geometric_brownian_motion vol 
                              rate 
                              incr 
                              init_pos =
    let gbm_increment = geometric_brownian_increment_func vol rate incr
    let rnd_gen = System.Random()
    let normal_increment = normal_rand_gen rnd_gen
    Seq.scan gbm_increment init_pos 
        (Seq.init_infinite normal_increment)

It is also possible to remove the "imperitive" loop in the middle via recursion, but in this case it detracts somewhat from readability and may not perform as well on systems without support for tailcall:

1
2
3
4
5
6
7
8
9
10
11
let box_muller' =
    let rec aux sum_sqrd x =
        if sum_sqrd >= 1.0 || sum_sqrd = 0.0
        then
            let next() = 2.0*randgen.NextDouble() - 1.0
            let x = next()
            let y = next()
            aux (x*x + y*y) x
        else
            x*(sqrt (-2.0*(log sum_sqrd)/sum_sqrd))
    aux 0.0 0.0
By on 4/14/2009 10:44 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper