Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/juanmanzanero/lion-cpp into…
Browse files Browse the repository at this point in the history
… main
  • Loading branch information
diegolodares committed Oct 22, 2023
2 parents dfba091 + 5662126 commit 2f0223a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
3 changes: 3 additions & 0 deletions lion/foundation/utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,9 @@ constexpr T smooth_neg(const T &x, S eps2);
template<bool ActuallySmooth = true, bool UseSinAtanFormula = true, typename T, typename S>
constexpr T smooth_sign(const T &x, S eps);

template<bool ActuallySmooth = true, bool UseSinAtanFormula = true, typename T, typename S>
constexpr T smooth_sign_derivative(const T &x, S eps);

template<bool ActuallySmooth = true, typename T, typename S>
constexpr T smooth_abs(const T &x, S eps2);

Expand Down
36 changes: 33 additions & 3 deletions lion/foundation/utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -236,10 +236,8 @@ constexpr T smooth_sign(const T &x, S eps)

if constexpr (ActuallySmooth) {
if constexpr (UseSinAtanFormula) {
using std::sin;
using std::atan;

return sin(atan(x / eps));
return x / smooth_abs(x, eps * eps);
}
else {
using std::tanh;
Expand All @@ -255,6 +253,38 @@ constexpr T smooth_sign(const T &x, S eps)
}


template<bool ActuallySmooth, bool UseSinAtanFormula, typename T, typename S>
constexpr T smooth_sign_derivative(const T &x, S eps)
{
//
// Returns the sign derivative of input "x" (where sign(0) = 0),
// smoothed out near 0 with parameter "eps" (unless
// template parameter "ActuallySmooth" is false, in that
// case the function is the strict sign of "x").
//

if constexpr (ActuallySmooth) {
if constexpr (UseSinAtanFormula) {
using std::sqrt;

return eps * eps / ((eps * eps + x * x) * sqrt(eps * eps + x * x));
}
else {
using std::tanh;

const auto tanh_x_div_eps = tanh(x / eps);
return -(tanh_x_div_eps * tanh_x_div_eps - 1.0) / eps;
}
}
else {
(void)eps;

return (x >= 0.0 ? 1.0 : -1.0);
}
}



template<bool ActuallySmooth, typename T, typename S>
constexpr T smooth_abs(const T &x, S eps2)
{
Expand Down

0 comments on commit 2f0223a

Please sign in to comment.