Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Modules/Core/Common/include/itkMath.h
Original file line number Diff line number Diff line change
Expand Up @@ -937,7 +937,9 @@ Absolute(T x) noexcept
#if __cplusplus >= 202302L
return std::abs(x);
#else
return (x < 0) ? -x : x;
// Note: +0.0 and -0.0 are considered equal, according to ExactlyEquals. They are both considered equal to T{}.
// And they both have the same absolute value: +0.0.
return ExactlyEquals(x, T{}) ? T{} : (x < 0) ? -x : x;
#endif
}
}
Expand Down
19 changes: 19 additions & 0 deletions Modules/Core/Common/test/itkMathGTest.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,25 @@ TEST(itkMath, Abs)
EXPECT_EQ(itk::Math::Absolute(-5), 5);
}


// Checks that `Math::Absolute(-0.0)` returns `+0.0`.
TEST(itkMath, AbsoluteMinusZeroReturnsPlusZero)
{
constexpr auto expectAbsoluteReturnsPlusZero = [](const auto minusZero) {
// Sanity check beforehand: assert that `minusZero` has indeed a minus sign.
ASSERT_TRUE(std::signbit(minusZero));

const auto absoluteValue = itk::Math::Absolute(minusZero);
EXPECT_FALSE(std::signbit(absoluteValue));
EXPECT_EQ(absoluteValue, 0);
};

// Check both float and double:
expectAbsoluteReturnsPlusZero(-0.0F);
expectAbsoluteReturnsPlusZero(-0.0);
}


TEST(itkMath, ConstexprTests)
{
static_assert(itk::Math::ExactlyEquals(5, 5));
Expand Down
Loading