user3532922
user3532922

Reputation: 11

Standard deviation calculation outputing incorrectly

I am trying to calculate the standard deviation of an array but my answer is returning as 0. I think the problem is stemming from the "count" getting messed up. The array I am receiving the data from is simply four numbers of 1,4,6,7. The code is outputting the answer as 0 but that is incorrect. Any help would be much appreciated.

#include <iostream> 
#include <iomanip>
#include <fstream>
#include <cmath>
#include <string>

using namespace std;
double mean(double *mydata, double N);
double standard_dev(double *mydata, double m, int N);

int main()
{
    int N(0);
    char filename [100];
    double m, stdev;
    double next;

    int count=0;
    cout<<"Enter name of file: ";
    cin>>filename;

    ifstream myfile;
    myfile.open(filename);
    while(myfile>>next)
    {
        count++;
    }

    N=count;
    double *mydata;
    mydata=new double[N];

    for(int i=0; i<N; i++)
    {
        myfile>>mydata[i];
    }
    m =  mean(mydata, N);
    stdev = standard_dev(mydata, m, N);
    cout<<"The standard deviation is:" <<stdev<<endl;

    myfile.close();
    delete[] mydata;
    return 0;
}

double mean(double *mydata, double N)  
{
    double sum(0), m;
    for(int i=0; i<N; i++)
    {
        sum +=mydata[i];
    }
    m=(sum/(double)N);
    return (m);
}
double standard_dev(double *mydata, double m, int N)
{
    double *mydata2= new double [N];
    for(int i=0; i<N; i++)
    {
        mydata2[i]= pow((mydata[i]-m),2);
    }
    double sum(0), S, X;
    for(int i=0; i<N; i++)
    {
        sum+=mydata2[i];
    }
    X=sum/N;
    S=sqrt(X);
    return (S);
}

The code for the array containing the 4 numbers is just: 1 4 6 7 They are vertical in coding.

Upvotes: 1

Views: 110

Answers (1)

yizzlez
yizzlez

Reputation: 8805

You are reading in the data wrong. First, you read in all the data to next to increment count. Then you try to read in the nonexistent data with you for loop. I recommend that you use std::vector to avoid the problem of dynamic memory allocation;

vector<double> mydata;
while(myfile>>next)
{
    mydata.push_back(next);
}

The other easiest solution is just to put the number of elements in the file. Ex:

File:

4 1 4 6 7

And read N from the file and use your for loop

Upvotes: 2

Related Questions