使用 Catch 比较双精度向量

问题描述 投票:0回答:3

我正在使用 Catch 单元测试框架,我想比较双精度向量。这个“其他答案”建议使用 Approx 来比较浮点/双精度值,但这不适用于它们的向量。有什么方便的方法可以实现这一点吗? 编辑:一个例子

使用以下代码:

#define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("Compare Vectors", "[vector]") { std::vector<int> vec1 = {0, 1, 2, 3}; std::vector<int> vec2 = {0, 1, 2, 4}; REQUIRE(vec1 == vec2); }

测试失败并显示以下报告:

------------------------------------------------------------------------------- Compare Vectors ------------------------------------------------------------------------------- test/UnitTests/test_Example/example.cc:4 ............................................................................... test/UnitTests/test_Example/example.cc:7: FAILED: REQUIRE( vec1 == vec2 ) with expansion: { 0, 1, 2, 3 } == { 0, 1, 2, 4 } =============================================================================== test cases: 1 | 1 failed assertions: 1 | 1 failed

但是如果我按如下方式更改代码,我希望测试能够通过,但显然没有。

#define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("Compare Vectors", "[vector]") { std::vector<double> vec1 = {0, 1, 2, 3}; std::vector<double> vec2 = {0, 1, 2, 3.000001}; REQUIRE(vec1 == vec2); }

我可以循环遍历这些元素并逐一比较它们,但如果出现差异,确定错误的来源将会更加困难。

c++ unit-testing catch-unit-test
3个回答
5
投票
Catch 2.7.2

以来,用户现在可以使用 Approx 比较向量:

REQUIRE_THAT(vec1, Catch::Approx(vec2).margin(0.0001));

这将比较两个向量的误差在 ± 0.0001 以内。
更多详情
这里


2
投票
REQUIRE(compareVectors(vec1, vec2));


bool compareVectors(std::vector<double> a, std::vector<double> b) { if (a.size() != b.size()) return false; for (size_t i = 0; i < a.size(); i++) { if (a[i] != Approx(b[i])) { std::cout << a[i] << " Should == " << b[i] << std::endl; return false; } } return true; } bool compare2dVectors(std::vector<std::vector<double>> a, std::vector<std::vector<double>> b) { if (a.size() != b.size()) return false; for (size_t i = 0; i < a.size(); i++) { if (! compareVectors(a[i], b[i])) return false; } return true; }

这样您至少能够看到失败的向量的名称,以及第一个不同的值。

这不是理想的解决方案,所以我仍然希望有人能够想出更好的东西,但我想我至少会分享我到目前为止所想出的东西,以防它对某人有帮助。


0
投票
范围和向量匹配器

例如,两个整数向量可以像这样进行比较:

#include <catch2/catch_test_macros.hpp> #include <catch2/matchers/catch_matchers.hpp> #include <catch2/matchers/catch_matchers_vector.hpp> std::vector<int64_t> result = func(); std::vector<int64_t> expected = {3306, 267, 1002, 256}; REQUIRE_THAT(result, Catch::Matchers::Equals(expected));

© www.soinside.com 2019 - 2024. All rights reserved.