I have homework to do in OCaml, and one question is about calculating the average of a list. I did that already 1 or 2 years ago in another language, and as I did the first time, I decided to not only sum all elements and divide by the length. The main reason is the fear of a floating-point overflow.
So I found the formula I used the last time on Wikipedia : recursive average formula.
I coded it this way in OCaml :
let average = function
| [] -> raise Empty_list
| hd::l ->
let rec aux average count = function
| hd::l -> aux ((average*.(float (count-1))+.hd)/.(float (count))) (count+1) l
| _ -> average
in aux hd 1 l
;;
which for me looks like the exact transcription of the formula in OCaml.
But it didn't work, however, after taking a paper, a pen and thinking about it I managed to get it working by replacing the line:
| hd::l -> aux ((average*.(float (count-1))+.hd)/.(float (count))) (count+1) l
with:
| hd::l -> aux ((average*.(float (count))+.hd)/.(float (count+1))) (count+1) l
and it worked.
I told myself the second line is logically the good one to compute the right answer, but I can't understand what was wrong in the first place. Did I translate a biased formula? Or did I miss something when translating?
At this point, it still looks for me like the first line is the transcription of the formula, and the second line is the way to compute the right answer. But I believe there's something I can't understand here. May someone shed light on this for me?