Johnny Chan
Johnny Chan

Reputation: 77

C++ assert failing when argument is true

I am writing some statistical functions in C++, specifically the corrected sample standard deviation function. I also write test suites with assertions to make sure that my code works as expected. I use online calculator to pre-determine the correct values for my test suites and check it against the output values from my stdev function using the assert keyword. I also printed out the values of my function output and they are identical to what I set them to be within the assert statement. The asserts should all be true since I am basically running assert(c == c) but it always fails. I am giving my test suites here as well as my stdev function.

void test_stdev_function() {
  vector<double> v1, v2, v3, v4;
  v1 = {0, 1, 2};
  v2 = {1, 1, 1};
  v3 = {-2, -1, 1, 2};
  v4 = {1, 1, 1, 10};
  assert(stdev(v1) == 1);
  assert(stdev(v2) == 0);
  assert(stdev(v3) == 1.82574);
  assert(stdev(v4) == 4.5);
  cout << "function stdev pass!" << endl;
}

double stdev(std::vector<double> v)
{
    double sum_square_diff = 0;
    double avg = 0;
    double sum = 0;
    int n = v.size();
    for (std::vector<double>::iterator itr = v.begin(); itr != v.end(); ++itr) {
        sum+=*itr;
        cout << "sum = " << sum << "  *itr = " << *itr << endl;
    }
    avg = sum / n;
    cout << "avg = " << avg << "    ";
    for (std::vector<double>::iterator itr = v.begin(); itr != v.end(); itr++) {
        sum_square_diff+=pow((*itr - avg), 2);
    }
    double stdev = sqrt(sum_square_diff / (n-1));
    cout << "stdev = " << stdev << endl;
    return stdev;
}

Anyone knows why the assert statements keep failing?

Upvotes: 0

Views: 1888

Answers (2)

Alessandro Scarlatti
Alessandro Scarlatti

Reputation: 734

Something like this could account for floating point uncertainty:

assert((fabs(stdev(v3) - 1.82574) < 0.00001));

Upvotes: 2

kaineub
kaineub

Reputation: 162

The first two asserts work because the stdev return values are whole numbers. The third one fails because there are a different number of decimal places returned from stdev than what you have written. The comparison fails and assert calls abort().

Upvotes: 1

Related Questions