Skip to content

Commit

Permalink
Fix root and cbrt
Browse files Browse the repository at this point in the history
  • Loading branch information
dancazarin committed Oct 11, 2023
1 parent 3ec664d commit c95fc45
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
10 changes: 8 additions & 2 deletions include/kfr/math/impl/log_exp.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -244,13 +244,19 @@ KFR_INTRINSIC vec<T, N> pow(const vec<T, N>& a, const vec<T, N>& b)
template <typename T, size_t N>
KFR_INTRINSIC vec<T, N> root(const vec<T, N>& x, const vec<T, N>& b)
{
return exp(reciprocal(b) * log(x));
const vec<T, N> t = exp(reciprocal(b) * log(abs(x)));
const mask<T, N> isint = floor(b) == b;
const mask<T, N> iseven = (broadcastto<itype<T>>(b) & 1) == 0;
return select(x > T(), t,
select(x == T(), T(),
select(isint, select(iseven, broadcast<N>(constants<T>::qnan), -t),
broadcast<N>(constants<T>::qnan))));
}

template <typename T, size_t N>
KFR_INTRINSIC vec<T, N> cbrt(const vec<T, N>& x)
{
return pow<T, N>(x, T(0.333333333333333333333333333333333));
return root<T, N>(x, T(3));
}

template <typename T, size_t N, KFR_ENABLE_IF(!is_f_class<T>), typename Tout = flt_type<T>>
Expand Down
10 changes: 10 additions & 0 deletions tests/unit/math/log_exp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,15 @@ KFR_AUTO_TEST_1(log, narrow, 2, 1)
KFR_AUTO_TEST_1(log2, narrow, 2, 1)
KFR_AUTO_TEST_1(log10, narrow, 3, 1)
KFR_AUTO_TEST_1(cbrt, narrow, 5, 1)

TEST(cbrt)
{
CHECK(kfr::cbrt(27.f) == 3.f);
CHECK(kfr::cbrt(-27.f) == -3.f);

CHECK(kfr::root(32.f, 5.f) == 2.f);
CHECK(kfr::root(-32.f, 5.f) == -2.f);
CHECK(std::isnan(kfr::root(-32.f, 5.001f)));
}
} // namespace CMT_ARCH_NAME
} // namespace kfr

0 comments on commit c95fc45

Please sign in to comment.