Add an ALMOST_EQUAL for comparing floats.

master
Zed A. Shaw 1 month ago
parent be0dbc9255
commit 0347e4efb8
  1. 2
      fuc2.wrap
  2. 13
      include/fuc2/testing.hpp
  3. 2
      meson.build
  4. 8
      tests/sample1.cpp

@ -1,5 +1,5 @@
[wrap-git]
directory=fuc2-0.1.0
directory=fuc2-0.2.0
url=https://lcthw.dev/cpp/fuc2.git
revision=HEAD
depth=1

@ -57,6 +57,19 @@ namespace fuc2 {
}
}
void ALMOST_EQUAL(auto v1, auto v2, int decimal_places, const std::string &message="",
const std::source_location location = std::source_location::current())
{
double multiplier = std::pow(10.0, decimal_places);
auto r_v1 = std::round(v1 * multiplier) / multiplier;
auto r_v2 = std::round(v2 * multiplier) / multiplier;
if(r_v1 != r_v2) {
auto test_value = fmt::format("{} != {} rounded {} places {} != {}", v1, v2, decimal_places, r_v1, r_v2);
throw std::runtime_error(craft_error("ALMOST_EQUAL", test_value, message, location));
}
}
void BLOWS_UP(std::function<void()> cb, const std::string &message="",
const std::source_location location = std::source_location::current());
}

@ -1,5 +1,5 @@
project('fuc2', 'cpp',
version: '0.1.0',
version: '0.2.0',
default_options: [
'cpp_std=c++23',
'cpp_args=-D_GLIBCXX_DEBUG=1 -D_GLIBCXX_DEBUG_PEDANTIC=1',

@ -42,6 +42,13 @@ namespace sample1 {
EQUAL(ages.size(), size_t(0), "wrong count");
}
void test_almost_equal() {
double x = 0.12345;
double y = 0.12346;
ALMOST_EQUAL(x, y, 4);
}
void test_push_blows_up() {
std::deque<float> ages;
@ -60,6 +67,7 @@ namespace sample1 {
.options={ .fail_fast=false },
.tests={
TEST(test_push_pop_back),
TEST(test_almost_equal),
TEST(test_push_pop_front),
TEST(test_push_blows_up),
}

Loading…
Cancel
Save