catchorg / Catch2

A modern, C++-native, test framework for unit-tests, TDD and BDD - using C++14, C++17 and later (C++11 support is in v2.x branch, and C++03 on the Catch1.x branch)
https://discord.gg/4CWS9zD
Boost Software License 1.0
18.65k stars 3.05k forks source link

How to compare two floating point vectors #2716

Open newyorker123 opened 1 year ago

newyorker123 commented 1 year ago

Description RangeEquals works well on int vector. But how to compare two double vectors? I want to achieve the following effect:

vector<double> vec1;
vector<double> vec2;
for e1 in vec1, e2 in vec2:
    REQUIRE_THAT(e1, WithinABS(e2 , 0.0001))

Additional context I tried to use AllMatch. But i don't know how to pass the second vector element-wise to the matcher

REQUIRE_THAT(vec1,AllMatch(WithinAbs(vec2 ???,0.0001)));
koteshiitm commented 1 year ago

You can add header #include <catch2/matchers/catch_matchers_all.hpp> and add this below line to check in your code to assert the value. REQUIRE_THAT(vec1, Catch::Matchers::WithinAbs(vec2, 0.0001));

LinuxDevon commented 1 year ago

The documentation here: https://github.com/catchorg/Catch2/blob/devel/docs/matchers.md#floating-point-matchers. Might make sense to have an example there on that page as well. I will try and add that.

You will want something like this:

std::vector<float> some_vec{ 1.111, 2.222, 3.333 };
std::vector<float> to_compare{1.111, 2.222, 3.333};
REQUIRE_THAT(some_vec, Approx(to_compare).margin(0.0001));

See this #760 for more details.