Calculating a moving average

Summarizing a list of numbers into one representative number can be done by calculating the average. The equation for the arithmetic mean is to add up all the values and divide by the number of values. However, if the values being summed over are extremely large, the total sum may overflow.

In Haskell, the range for Int is at least from -2^29 to 2^29-1. Implementations are allowed to have an Int type with a larger range. If we try to naively average the numbers 2^29-2 and 2^29-3 by first calculating their sum, the sum may overflow, producing an incorrect calculation for the average.

A moving average (or running average) tries to escape this drawback. We will use an exponential smoothing strategy, which means numbers ...

Get Haskell Data Analysis Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.