HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Deviation and Variance

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
andvariancedeviation

Problem

This assignment requires obtaining the deviation and variance of \$n\$ numbers stored in one single array. Is there any way to make this code more efficient?

#include 
#include 

using namespace std;
int main()

{
    const int arrSize = 14;
    double average , sum = 0 , dev = 0;
    double deviation[arrSize];

    int grades[arrSize] = { 89, 95, 72, 83, 99, 54, 86, 75, 92, 73, 79, 75, 82, 73 };

    // Calculating the average
    for ( int i = 0; i < arrSize; i++ )
    {
        sum += grades[i];
        average = ( sum / arrSize );
    }
    cout << "average is : " << average << endl;
    cout << endl;

    //Calculating the deviation and variance

    double sumVar = 0 , totalVar = 0;
    for ( int i = 0; i < arrSize; i++ )
    {
        deviation[i] = ( grades[i] - average );

        cout << "Grades = " << grades[i] << " and deviation is = " << deviation[i] << endl;

        double variance = pow( deviation[i] , 2 );
        sumVar = sumVar + variance;
        totalVar = ( sumVar / arrSize );

    }
    cout << endl;
    cout << "variance = " << totalVar << endl;

    system( "pause" );
    return 0;
}

Solution

efficiency

Yes, this can be improved.

One obvious problem is that you're re-computing your average and your standard deviation on every iteration of a loop, even though only the last result (after the last iteration) is ever actually used.

For example:

for (int i = 0; i < arrSize; i++)
{
    sum += grades[i];
    average = (sum / arrSize);
}


You're computing average on every iteration, but only need or use the last value you compute. You can compute it once with code like:

for (int i = 0; i < arrSize; i++)
{
    sum += grades[i];
}
average = (sum / arrSize);


Your computation of the standard deviation is much the same way.
Use of pow

I'd avoid using pow to compute a square. It often imposes quite a bit of overhead, so pow(deviation[i], 2) will often be substantially slower than deviation[i]*deviation[i].
Formatting

Looking at the code more generally, you really need to fix your indentation.
std::endl

I would advise against using std::end. Normally, you just want '\n', which also gives you a new line, but will nearly always be (much) faster. In the case above, it won't make much difference, but if you're writing a lot of data to a file (for example) the difference can get very large, very quickly (e.g., a slowdown of 8:1 or 10:1 is fairly typical).

Code Snippets

for (int i = 0; i < arrSize; i++)
{
    sum += grades[i];
    average = (sum / arrSize);
}
for (int i = 0; i < arrSize; i++)
{
    sum += grades[i];
}
average = (sum / arrSize);

Context

StackExchange Code Review Q#149940, answer score: 5

Revisions (0)

No revisions yet.