Home Ask Login Register

Developers Planet

Your answer is one click away!

Pietair February 2016

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.


Sven Nilsson February 2016

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!

Pierre February 2016

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); // choose here your tolerance

You can adapt it to compare your vectors.

ollo March 2016

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;

Post Status

Asked in February 2016
Viewed 1,782 times
Voted 13
Answered 3 times


Leave an answer

Quote of the day: live life