Pietair
Pietair

Reputation: 406

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.

Upvotes: 0

Views: 3167

Answers (3)

Pierre
Pierre

Reputation: 1174

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.

Upvotes: 2

ollo
ollo

Reputation: 25370

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);

Upvotes: 3

Sven Nilsson
Sven Nilsson

Reputation: 1879

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!

Upvotes: 1

Related Questions