Étude 7-3: Using lists:foldl/3
Add mean/1
and stdv/1
functions to the stats
module which
you created in Étude 6-2 to calculate the mean and
standard deviation for a list of numbers.
1>
c
(
stats
).
{ok,stats}
2>
stats
:
mean
([
7
,
2
,
9
]).
6.0
3>
stats
:
stdv
([
7
,
2
,
9
]).
3.605551275463989
The formula for the mean is simple; just add up all the numbers and
divide by the number of items in the list (which you may find by using the
length/1
function).Use lists:foldl/3
to calculate the sum of the items
in the list.
The following is the algorithm for calculating
the standard deviation. Presume that N
is the number of items
in the list.
- Add up all the numbers in the list (call this the sum).
- Add the squares of the numbers in the list (call this the sum of squares).
-
Multiply
N
times the sum of squares. - Multiply the sum times itself.
- Subtract the result of step 4 from the result of step 3.
-
Divide the result of step 5 by
N * (N - 1)
. - Take the square root of that result.
Thus, if your numbers are 7, 2, and 9, N
would be three, and
you would do these calculations:
- The sum is 7 + 2 + 9, or 18.
- The sum of squares is 49 + 4 + 81, or 134.
-
N
times the sum of squares is 134 * 3, or 402. - The sum times itself is 18 * 18, or 324.
- 402 - 324 is 78.
- 78 divided by (3 * (3 - 1)) is 78 / 6, or 13.
- The standard deviation is the square root of 13, or 3.606.
In your code, you can do steps three through seven in one arithmetic expression. You’d have variables in your expression rather than constants, of course. ...
Get Études for Erlang 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.