Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include "ccmath/math/compare/isnan.hpp"
#include "ccmath/math/power/sqrt.hpp"

#include <limits>
#include <type_traits>

namespace ccm::internal::impl
Expand Down Expand Up @@ -44,6 +45,14 @@ namespace ccm::internal::impl
}

const T ratio = y / x;
return x * ccm::sqrt(static_cast<T>(1) + ratio * ratio);

// Compute scale in double precision to avoid float rounding scale to exactly
// 1.0 when ratio is tiny, which would make the overflow guard silently fail.
const double ratio_d = static_cast<double>(ratio);
const double scale_d = ccm::sqrt(1.0 + ratio_d * ratio_d);

if (static_cast<double>(x) > static_cast<double>(std::numeric_limits<T>::max()) / scale_d) { return fp_bits_t::inf().get_val(); }

return x * static_cast<T>(scale_d);
}
} // namespace ccm::internal::impl
10 changes: 10 additions & 0 deletions tests/src/math/power/hypot_cbrt_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,13 @@ TEST(CcmathPowerTests, HypotCbrtCompileTime)
static_assert(ccm::hypot(2.0, 3.0, 6.0) == 7.0);
static_assert(ccm::cbrt(8.0) == 2.0);
}
TEST(CcmathPowerTests, HypotOverflowBoundary)
{
constexpr float x = 3.40282347e38f;
constexpr float y = 9.18e34f;

ccm::test::ExpectSameFloatingAsStd(
ccm::hypot(x, y),
std::hypot(x, y)
);
}