Pietair Pietair - 1 year ago 187
C++ Question

Checking if two vectors are equal

I have two vectors:

std::vector<double> calculatedValues = calculateValues();
std::vector<double> expectedValues = {1.1, 1.2};

I am using cpputest to verify if these vectors are equal:

CHECK_TRUE(calculatedValues == expectedValues)

This is working. However, I am wondering whether I shouldn't use some tolerance, because after all I am comparing doubles.

Answer Source

To compare floating point values you should do something like this:

bool is_equal(double a, double b) {

    return (abs(a-b)/b < 0.0001); // 0.00001 value can be a relative value

You can adapt it to compare your vectors.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download