Jonco98
Jonco98

Reputation: 402

What is wrong with my math?

Ok, so my instructor assigned us to make a program that used a set of numbers and finds the standard deviation of it. My program finds the Mean just fine. However, there is an issue with my math. What is wrong with it. It is giving me a mean of 59 and a deviation of 8.4. The mean is right however the deviation should be 96.4. Whats wrong with my math.

EDIT: My Program now works.
P.S. I have changed the following code to my current version of code.

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <math.h>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
//Used To Round The Decimal Points
cout << setiosflags(ios::fixed|ios::showpoint);
cout << setprecision(1);

//Declaring
double Numbers[] = {65, 49, 74, 59, 48}; //Work On Making This A User Input----------Deivation = 96.4
double Mean = 0, Items = 0, Sum = 0, Deviation = 0;
int Counter;

//Finds The Mean Of The Set Of Numbers
for (Counter = 0; Counter < sizeof(Numbers) / sizeof(double); Counter++)
{
    for (Counter = 0; Counter < sizeof(Numbers) / sizeof(double); Counter++)
    {
        Sum += Numbers[Counter]; //Adds All Numbers In Array Together
    }
    Items = sizeof(Numbers) / sizeof(double); //Gets The Number Of Items In The Array
    Mean = Sum / Items; //Finds The Mean
}

//Finds The Standard Deviation
for (Counter = 0; Counter < sizeof(Numbers) / sizeof(double); Counter++)
{
    Deviation += pow((Numbers[Counter] - Mean), 2) / Items; //Does Math Things...
}
Deviation = sqrt(Deviation);
cout << "Deviation = " << Deviation << endl; //Print Out The Standard Deviation

system("pause");
return 0;
}

Upvotes: 0

Views: 175

Answers (4)

user3875690
user3875690

Reputation: 139

The fault is as people have pointed out that standard deviations cannot be added directly. A better way to calculate the standard deviation is to take the root mean square (of element subtracted from its mean).

Upvotes: 0

floppy12
floppy12

Reputation: 1053

There is a fault in mathematic expression of deviation which should be the square root of variance of the set :

Variance = sum ( pow(set[i] - mean, 2) ) / n

deviation = sqrt(Variance)

By the way I think 9.82 here is more correct than 96.4

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

[...] however the deviation should be 96.4

It's the variance that should be 96.4. It is calculated as the average of squared differences from the mean, so you don't need square root at all:

for (Counter = 0; Counter < sizeof(Numbers) / sizeof(double); Counter++)
{
    Variance += pow((Numbers[Counter] - Mean), 2) / Items;
}
Deviation = sqrt(Variance);

Taking square root of variance yields 9.81835.

Upvotes: 4

C. Rahn
C. Rahn

Reputation: 301

Draw the sqrt out of the loop and apply it after the summing.

Upvotes: 1

Related Questions