[Haskell-cafe] Help to create a function to calculate a n element
moving average ??
S. Doaitse Swierstra
doaitse at swierstra.net
Tue Sep 28 15:19:27 EDT 2010
Avoiding repeated additions:
movingAverage :: Int -> [Float] -> [Float]
movingAverage n l = runSums (sum . take n $l) l (drop n l)
where n' = fromIntegral n
runSums sum (h:hs) (t:ts) = sum / n' : runSums (sum-h+t) hs ts
runSums _ _ [] = []
Doaitse
On 28 sep 2010, at 03:40, Richard O'Keefe wrote:
>
> On 27/09/2010, at 5:20 AM, rgowka1 wrote:
>
>> Type signature would be Int -> [Double] -> [(Double,Double)]
>>
>> Any thoughts or ideas on how to calculate a n-element moving average
>> of a list of Doubles?
>>
>> Let's say [1..10]::[Double]
>>
>> what is the function to calculate the average of the 3 elements?
>>
>> [(1,0),(2,0),(3,2),(4,3)....] :: [(Double,Double)]
>
>> moving_average3 (xs0 @ (_ : (xs1 @ (_ : xs2)))) =
>> zipWith3 (\x y z -> (x+y+z)/3) xs0 xs1 xs2
>
> *Main> moving_average3 [1..10]
> [2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0]
>
> The result is two elements shorter than the original, but that
> _is_ the definition of moving average after all.
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
More information about the Haskell-Cafe
mailing list