8 people like it.

Moving Average

Given a period and a sequence of values, calculates the moving average of the input. E.g., given a period of 4 and a sequence of { 2.0, 8.0, 12.0, 10.0, 6.0, 4.0, 14.0 }, the result of this function is { 8.0, 9.0, 8.0, 8.5 }.

1: 
2: 
3: 
4: 
let movingAverage (period : int) (values : float seq) =
    Seq.zip values (Seq.skip period values)
    |> Seq.scan (fun last (prev, cur) -> last - prev + cur) (values |> Seq.take period |> Seq.sum)
    |> Seq.map (fun x -> x / float(period))
val movingAverage : period:int -> values:seq<float> -> seq<float>

Full name: Script.movingAverage
val period : int
Multiple items
val int : value:'T -> int (requires member op_Explicit)

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

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
val values : seq<float>
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<_>
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<_>
module Seq

from Microsoft.FSharp.Collections
val zip : source1:seq<'T1> -> source2:seq<'T2> -> seq<'T1 * 'T2>

Full name: Microsoft.FSharp.Collections.Seq.zip
val skip : count:int -> source:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Collections.Seq.skip
val scan : folder:('State -> 'T -> 'State) -> state:'State -> source:seq<'T> -> seq<'State>

Full name: Microsoft.FSharp.Collections.Seq.scan
val last : float
val prev : float
val cur : float
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 map : mapping:('T -> 'U) -> source:seq<'T> -> seq<'U>

Full name: Microsoft.FSharp.Collections.Seq.map
val x : float
Raw view Test code New version

More information

Link:http://fssnip.net/4S
Posted:13 years ago
Author:Brett V. Forsgren
Tags: sequences , average