Checking if two vectors are equal

2.8k Views Asked by At

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.

3

There are 3 best solutions below

1
On BEST ANSWER

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.

0
On

Yes, you should use some tolerance because floating point operations are not guaranteed to yield the exact same results on different CPUs. There can be e.g. roundoff errors.

However, the SSE/SSE2 standards do provide reproducible floating point math, so you may consider using the compile flag /ARCH:SSE2 as an alternative. That said, it is difficult to ensure that no x87 math is used anywhere in the app, so be careful!

0
On

Instead of operator== you can use std::equal() with a custom epsilon:

bool equal = std::equal(calculatedValues.begin(), calculatedValues.end(), expectedValues.begin(),
                        [](double value1, double value2)
                        {
                            constexpr double epsilon = 0.01; // Choose whatever you need here
                            return std::fabs(value1 - value2) < epsilon;
                        });
CHECK_TRUE(equal);