Live with Dot Net Just another Programming weblog

Calculate Standard Deviation for the given data points

Posted on February 14, 2010

Below code will give us the Standard Deviation for the list data (double type) provided.
You need to be carefully in handle 'Divide by zero' error.

Formulae for the Standard Deviation:

Standard Deviation

Code here :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/// <summary>
        /// Return the Standard Deviation for the provide set of data array to the calling function.
        /// Parameter : Double Array 
        /// </summary>
        public static double StandardDeviation(double[] data)
        {
            double ret = 0;
            double DataAverage = 0;
            double TotalVariance = 0;
            int Max = 0;
 
            try
            {
                Max = data.Length;
                if (Max == 0) { return ret; }
                DataAverage = Average(data);
 
                for (int i = 0; i < Max; i++)
                {
                    TotalVariance += Math.Pow(data[i] - DataAverage, 2);
                }
 
                ret = Math.Sqrt(SafeDivide(TotalVariance, Max));
            }
            catch (Exception) { throw; }
            return ret;
        }
 
        private static double Average(double[] data)
        {
            double ret = 0;
            double DataTotal = 0;
 
            try
            {
                for (int i = 0; i < data.Length; i++)
                {
                    DataTotal += data[i];
                }
 
                return SafeDivide(DataTotal, data.Length);
            }
            catch (Exception) { throw; }
            return ret;
        }
 
        private static double SafeDivide(double value1, double value2)
        {
            double ret = 0;
 
            try
            {
                if ((value1 == 0) || (value2 == 0)) { return ret; }
                ret = value1 / value2;</code>
            }
            catch { }
            return ret;
        }

About admin

No description. Please complete your profile.
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.