Logic Erros

Feb 18, 2017 at 10:08pm
The standard deviation calculation on this program doesn't seem to yield an accurate result. Someone please spot the logic error here. Also maybe help neaten this up. Feels like i have too many variables going on here


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
45
46
47
48
49
50
51
52
  #include <iostream>
#include <iomanip>
#include <fstream>
#include <math.h>

using namespace std;
// program that calculates the standard deviation from a set of numbers on a text file.

//To calculate the standard deviation:
//1. calculate the average or mean
//2. For each number subtract the mean and square the result.
//3. work out the mean of those squared differences
//4. Take the square root of result in 3 above.

int main ()
{
    double input [100];
    int x = 0;
    double average , sum = 0 ;
    double deviation = 0 , mean , result;

    fstream textfile;
    textfile.open("numbers.txt");

    while ( !textfile.eof ())
    {
       textfile >> input [x];
       cout << input[x] << endl;

      sum = sum + input [x];

      average = sum / 10;

   // For each number subtract the mean and square the result.
     deviation = deviation + ((input [x] - average ) * (input [x] - average )) ;
   // work out the mean of those squared differences
       mean =  (deviation / 10);
    // Take the square root of result in above to get standard deviation.
        result = sqrt (mean);

       x++;

    }

 cout << " The average of the numbers is:  " << average << endl;
 cout << " The standard deviation of the numbers is:  " << result << endl;
 textfile.close();

    return 0;
}

Feb 18, 2017 at 10:19pm
line 32: the average should not be

average = sum / (x + 1)?

this is because the average varies with the number of inserted items ...
Last edited on Feb 18, 2017 at 10:22pm
Feb 18, 2017 at 11:04pm
Read the numbers with
while (textfile >> input[x]) {
You can't compute the deviation until you know the average of all the numbers, so you would need another loop to take care of that. Actually, if you do a little algebra on the deviation formula, you'll find that if you keep track of sum of x and the sum of x2, then you can compute the average and standard deviation directly from the sums.
Feb 20, 2017 at 10:17am
Mmmh ok will re-work this and see what results i get. The test input file is hard coded so input values have already been inserted. will however try this out and see......Thanks guys
Topic archived. No new replies allowed.