Arithmetic Mean, Geometric Mean, Harmonic Mean and Weighted Arithmetic Mean (Statistics in Erlang Part 1)
August 10, 2008 4:34 pm Erlang, Math, Programming, Statistics, Tools and Libraries[digg-reddit-me]I’ll be putting up some statistical functions I’ve had to write recently. This is the first batch. I confess, I find the erlang implementations far more readable than the pure math definitions one finds around; I’ve been thinking about writing tutorials, but with this code here, I’m not entirely sure it’s necessary.
At any rate, the code follows. As with so much of my erlang code, this code is part of the ScUtil library. ScUtil is free and MIT license, because the GPL is evil.
There’re more statistics coming, I just don’t want to make any one post too huge, and I don’t want keyword saturation.
This partially closes issue 119. This closes issue 133. This closes issue 136. This closes issue 137.
list_product(List) when is_list(List) ->
list_product(List, 1).
list_product([], Counter) ->
Counter;
list_product([Head|Tail], Counter) ->
list_product(Tail, Counter*Head).
arithmetic_mean(List) when is_list(List) ->
lists:sum(List) / length(List).
geometric_mean(List) when is_list(List) ->
math:pow(scutil:list_product(List), 1/length(List)).
harmonic_mean(List) when is_list(List) ->
length(List) / lists:sum([ 1/X || X<-List ]).
weighted_arithmetic_mean(List) when is_list(List) ->
weighted_arithmetic_mean(List, 0, 0).
weighted_arithmetic_mean([], Num, Denom) ->
Num/Denom;
weighted_arithmetic_mean([{W,V}|Tail], Num, Denom) ->
weighted_arithmetic_mean(Tail, Num+(W*V), Denom+W).

August 10th, 2008 at 5:01 pm
[...] Mean, Median, Mode and Histograph (Statistics in Erlang Part 2) August 10, 2008 5:01 pm John Haugeland Erlang, Math, Programming, Statistics, Tools and Libraries digg_url = http://fullof.bs/mean-median-mode-and-histograph-statistics-in-erlang-part-2; reddit_url=“http://fullof.bs/mean-median-mode-and-histograph-statistics-in-erlang-part-2″Mean is a complex topic, and is covered in Statistics in Erlang part 1. [...]
August 10th, 2008 at 8:02 pm
Hi, you could use high order functions, like lists:fold, that keeps the accumulator for you. Using it you could write something like
list_product(List) ->
lists:foldl(fun(A,B) -> A*B end,1,List).
August 10th, 2008 at 8:19 pm
[...] code requires the arithmetic mean stuff from Statistics in Erlang part 1. There’s interesting, unrelated stuff in Part [...]
August 14th, 2008 at 10:09 pm
[...] code doesn’t need any of the prior parts 1, 2, or 3 of Statistics in Erlang, but I’m linking them to make them easy to [...]