0 people like it.

Pi - Using Nilakantha's accelerated series

Calculate the value of Pi, using the Nilakantha series

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
let nPi =     
    let piSeq = seq{
        yield 3.0
        let rec pi start sign = seq{
            yield (sign * 4.0) / ( start * (start + 1.0) * (start + 2.0))
            yield! pi (start + 2.0) (sign * -1.0)
        }

        yield! pi 2.0 1.0
    }
    piSeq |> Seq.take 10 |> Seq.sum

// using unfold
let p' = 
    let calc start sign = (sign * 4.0) / ( start * (start + 1.0) * (start + 2.0))

    Seq.unfold (fun (start, sign) -> Some ( (calc start sign), (start + 2.0, sign * -1.0) )) (2.0, 1.0)
    |> Seq.take 10 
    |> Seq.sum 
    |> (+) 3.0
val nPi : float

Full name: Script.nPi
val piSeq : seq<float>
Multiple items
val seq : sequence:seq<'T> -> seq<'T>

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

--------------------
type seq<'T> = System.Collections.Generic.IEnumerable<'T>

Full name: Microsoft.FSharp.Collections.seq<_>
val pi : (float -> float -> seq<float>)
val start : float
val sign : float
module Seq

from Microsoft.FSharp.Collections
val take : count:int -> source:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.take
val sum : source:seq<'T> -> 'T (requires member ( + ) and member get_Zero)

Full name: Microsoft.FSharp.Collections.Seq.sum
val p' : float

Full name: Script.p'
val calc : (float -> float -> float)
val unfold : generator:('State -> ('T * 'State) option) -> state:'State -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.unfold
union case Option.Some: Value: 'T -> Option<'T>

More information

Link:http://fssnip.net/7X6
Posted:5 years ago
Author:Apurva
Tags: math