Home

F# Example: Measure of Center

   

Introduction

This example calculates the measures of center: the sum, the mean, the median, and the midrange of a series.

// Measures of Center
// Using a List
let numbers = [ 1; 7; 4; 2; 3; 4 ]; // [ 18; 24; 20; 35; 19; 23; 26; 23; 19; 20 ];
// [ 40000; 29000; 35500; 31000; 43000; 30000; 27000; 32000 ];
// [ 3; 13; 7; 5; 21; 23; 39; 23; 40; 23; 14; 12; 56; 23; 29 ];
// [ 1; 5; 2; 8; 7 ];
// [ 72604; 7592; 6314; 57086; 24885 ];
let sum list =
    let mutable s = 0;
    for n in list do
        s <- s + n;
    s
let mean list =
    (sum list) / (List.length list)
let median list =
    let sorted = List.sort list
    let mutable result = 0.00;
    if (List.length sorted) % 2 = 0 then
        let midIndex = (float (List.length sorted) - 1.00) / 2.00
        let midIndexPlus1 = midIndex + 1.00;
        result <- (sorted.Item(int midIndex) + sorted.Item(int midIndexPlus1)) / 2.00;
    else
        result <- (float (sorted.Item(((List.length sorted) - 1) / 2)));
    result

let midrange list =
    let sorted = List.sort list
    float (sorted.Item(0) + (sorted.Item((List.length sorted) - 1))) / 2.00;

printf "Values:";
for v in numbers do
    printf " %d" v;
printfn "";
printfn "Sum: %d" (sum numbers);
printfn "Mean: %d" (mean numbers);
printfn "Median: %.03f" (float (median numbers));
printfn "Midrange: %.03f" (float (midrange numbers));
printfn "Numbers: %A" numbers;
let sorted = List.sort numbers
printfn "Sorted Numbers: %A" sorted
let length = List.length sorted
printfn "List length: %d" length;
let midIndex = ((List.length sorted) - 1) / 2
printfn "midIndex: %A" midIndex
let middle = sorted.Item(((List.length sorted) - 1) / 2)
printfn "Middle Item: %d" middle;
 
   
     
 

Home Copyright © 2015 FunctionX Home