Anonymous user
Averages/Pythagorean means: Difference between revisions
m
→{{header|OCaml}}: indentation
m (→{{header|OCaml}}: indentation) |
|||
Line 188:
The three means in one function
<lang ocaml>let means v =
let n = Array.length v
and a = ref 0.0
let nn = float_of_int n in (!a /. nn, !b ** (1.0/.nn), nn /. !c);;</lang>▼
and b = ref 1.0
and c = ref 0.0 in
for i=0 to n-1 do
a := !a +. v.(i);
b := !b *. v.(i);
c := !c +. 1.0/.v.(i);
done;
let nn = float_of_int n in
;;</lang>
Sample output
<lang ocaml>means (Array.init 10 (function i -> (float_of_int (i+1)))) ;;
(* (5.5, 4.5287286881167654, 3.4141715214740551) *)
(* Simpler implementation *)
let means v =
let means v = let (a, b, c) = Array.fold_left (fun (a, b, c) x -> (a+.x, b*.x, c+.1./.x)) (0.,1.,0.) v in▼
let (a, b, c) =
let n = float_of_int (Array.length v) in (a/.n, b**(1./.n), n/.c);;</lang>▼
Array.fold_left
▲
(0.,1.,0.) v
in
(a /. n, b ** (1./.n), n /. c)
;;</lang>
=={{header|Oz}}==
|