Standard deviations and variances

By sunslayer on Feb 21, 2011

calculates the standard devation and variances of the given data set and determines whether a number is an outlier in the set

#include <iostream>
#include <cstdarg>
#include <vector>
#include <cmath>

using namespace std;

struct sd
{
    sd();
    sd(int,...);
    ~sd(){s.clear();}
    public:
        int t;
        vector<double> s;
        double sum;
        double var(){
            double avg = mean(),to = 0;
            for(vector<double>::iterator start = s.begin();start<s.end();start++)
                to += pow(avg - *start,2);
            return to/t;
        }
        double mean(){return (sum/t);}
        double std(){return sqrt(var());}
        bool isOutlier(double x){
            double s = std()*3,avg = mean();
            return (x>(avg-s)&&x<(avg+s)?true:false);
        };
};

sd::sd()
{
    int c;
    double x;
    sum = 0;
    cout << "Enter number of data sets: ";
    cin >> t;
    if(!cin)
        cerr << "You must enter an integer!";
    else
    {
        vector<double> m(t);
        c = t;
        cout << "Enter data sets:\n";
        do
        {
            cin >> x;
            m[t-c] = x;
            sum+=x;
        }   while(--c>0);
        s = m;
        m.clear();
    }
}

sd::sd(int h,...)
{
    sum = 0;
    va_list vl;
    va_start(vl,h);
    double val;
    t = h;
    vector<double> m(h);
    for (int i=0;i<h;i++)
    {
        m[i] = double(val=va_arg(vl,double));
        sum+=val;
    }
    s = m;
    m.clear();
    va_end(vl);
}

int main()
{
    sd test(5,600.0, 470.0, 170.0, 430.0, 300.0);

    cout << test.var() << endl;     // returns variance
    cout << test.std() << endl;     // returns standard deviation
    cout << test.isOutlier(450.0);  // returns true if 450 is an outlier

    return 0;
}

Comments

Sign in to comment.
Hawkee   -  Feb 21, 2011

Excellent. Sometimes it is faster to code something up than do it manually, but each situation is different. I've sometimes had to do something by hand because the coding would just take a bit longer.

 Respond  
sunslayer   -  Feb 21, 2011

oh, I'm doing this is my math class atm and couldn't figure out how to do it on my calculator and calculating it by hand takes a long time

 Respond  
Hawkee   -  Feb 21, 2011

I mean is it for a class in school? I'm curious why you would need to build such a snippet.

 Respond  
sunslayer   -  Feb 21, 2011

it's a data structure, you use it the same as you would any other data type

sd test(5,600.0, 470.0, 170.0, 430.0, 300.0);

assigns the variable test with type sd

 Respond  
Hawkee   -  Feb 21, 2011

Is this for a class?

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.