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.
N
times the sum of squares.
N * (N - 1)
.
Thus, if your numbers are 7, 2, and 9, N
would be three, and
you would do these calculations:
N
times the sum of squares is 134 * 3, or 402.
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.
math:sqrt((3 * 134 - 18 * 18)/(3 * (3 - 1))
Use lists:foldl/3
to calculate the sum and the sum of squares.
Bonus points if you can calculate both of them
with one call to lists:foldl/3
. Hint:
the argument for the accumulator doesn’t have to be a single number. It can
be a list or a tuple.
3.133.140.153