Standard Deviation Program

May 1, 2011 at 5:07am
Good day! I have been trying to code a program with 2 functions: One which takes a vector of integers and calculates the average. The other is to calculate the standard deviation. The user is asked to enter an integer which is inputed as the size of the vector. The vector will then be filled with random integers. My problem is that the program works fine, except that it keeps returning the deviation as 0.
The formula for standard deviation is here: http://www.social-science.co.uk/research/?n1=&id=93
Thanks for your help!

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
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>
using namespace std;
//AVERAGE
double Average(vector<int> v)
{      int sum=0;
       for(int i=0;i<v.size();i++)
               sum+=v[i];
       return sum/v.size();
}
//DEVIATION
double Deviation(vector<int> v, double ave)
{
       double E=0;
       for(int i=0;i<v.size();i++)
               E+=(v[i] - ave)*(v[i] - ave);
       return sqrt(1/v.size()*E);
}
                
int main()
{
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(5);
    int n;
    srand(time(NULL));
    cout << "Enter an integer: " << endl; 
    cin >> n;
    vector<int> v(n); //vector of length n
    for(int i=0;i<n;i++)
            v[i] = rand();//fills vector with random integers
    //Average
    double AVG=Average(v); 
    cout << "Average of these numbers: " << AVG << endl;
    cout << "Standard deviation: " << Deviation(v,AVG) << endl; 
                               

    
    system("PAUSE");
    return EXIT_SUCCESS;
}
May 1, 2011 at 5:25am
closed account (3hM2Nwbp)
Hello, your problem seems to be that you were unknowingly throwing away the precision that you needed. 1 / vector::size will always evaluate to 0, unless vector::size is 1, then it will evaluate to 1. To fix that, we cast vector::size to a double.

1
2
3
4
5
6
7
8
9
10
11
double Deviation(vector<int> v, double ave)
{
    double E=0;
    // Quick Question - Can vector::size() return 0?
    double inverse = 1.0 / static_cast<double>(v.size());
    for(unsigned int i=0;i<v.size();i++)
    {
        E += pow(static_cast<double>(v[i]) - ave, 2);
    }
    return sqrt(inverse * E);
}
Last edited on May 1, 2011 at 5:33am
May 1, 2011 at 5:33am
I see. Thanks! And to your question, vector::size() cannot be zero or we will be dividing by 0!
Last edited on May 1, 2011 at 5:35am
Topic archived. No new replies allowed.