Pup Watthanawong
Pup Watthanawong

Reputation: 5

Standard Deviation equals to zero?

In my homework activity it asks me to write a code from the following instructions:

The standard deviation of a set of numbers is a measure of the spread of their values. It is defined as the square root of the average of the squared differences between each number and the mean. To calculate the standard deviation of the numbers stored in data:

  1. Calculate the mean of the numbers.

  2. For each number, subtract it from the mean and square the result.

  3. Find the mean of the numbers calculated in step 2.

  4. Find the square root of the result of step 3. This is the standard deviation.

Write code to calculate the standard deviation of the numbers in data and store the result in the double sd.

Example: double [] data= {1.0,2.0,3.0,4.0,5.0};

//expected standard deviation(output): 1.4142136

//My code:

double mean1=0;
double mean2=0;
double sum1=0;
double sum2=0;
double sd=0;
//calculate sum from arrays of doubles

for(double a:data)
{
    sum1+=a;
}

//calculate mean

mean1=sum1/data.length;

//creates new array for step2

double newData[]=new double[data.length];
for(int k= 0; k>newData.length; k++)
{
    double s=0;
    newData[k]=data[k];
    s=Math.pow((mean1-data[k]),2);
    newData[k]=s;

}

//calculate sum of the new array
for(double b:newData)
{
    sum2+=b;
}

//calculate mean
mean2=sum2/newData.length;

//calculate standard deviation by sqrt
sd+=Math.sqrt(mean2);

When I compile I got standard deviation of 0.0???!

This is where I don't understand. I did the code on paper- 1.I got a mean1 of 3.0 2.I subtract mean1 with the data[] and square to get {4,1,0,1,4} 3.I added and divided to find mean2 which equals 2

I √2 and got 1.4142136 just like the expected result.

THESIS: WHY DID I GET 0.0 for sd??

Upvotes: 0

Views: 294

Answers (1)

rgettman
rgettman

Reputation: 178293

Your for loop condition is incorrect; the for loop won't be entered, leaving newData full of zeros.

for(int k= 0; k>newData.length; k++)

Try <.

for(int k = 0; k < newData.length; k++)

Upvotes: 5

Related Questions