diff --git a/src/Math/Functions.h b/src/Math/Functions.h index d0dbc0e21..42ab8991d 100644 --- a/src/Math/Functions.h +++ b/src/Math/Functions.h @@ -161,6 +161,28 @@ template Vector max(const Vector& a } #endif +/** +@brief Sign + +Returns `1.0` if @f$ x > 0 @f$, `0.0` if @f$ @p x = 0 @f$ and `-1.0` if +@f$ x < 0 @f$. +*/ +#ifdef DOXYGEN_GENERATING_OUTPUT +template inline T sign(const T scalar); +#else +template inline typename std::enable_if::value, T>::type sign(const T& scalar) { + if(scalar > T(0)) return T(1); + if(scalar < T(0)) return T(-1); + return T(0); +} +template Vector sign(const Vector& a) { + Vector out; + for(std::size_t i = 0; i != size; ++i) + out[i] = sign(a[i]); + return out; +} +#endif + /** @brief Absolute value */ #ifdef DOXYGEN_GENERATING_OUTPUT template inline T abs(const T& a); diff --git a/src/Math/Test/FunctionsTest.cpp b/src/Math/Test/FunctionsTest.cpp index 898df5ef8..93c09d86b 100644 --- a/src/Math/Test/FunctionsTest.cpp +++ b/src/Math/Test/FunctionsTest.cpp @@ -35,6 +35,7 @@ class FunctionsTest: public Corrade::TestSuite::Tester { void min(); void max(); + void sign(); void abs(); void sqrt(); void clamp(); @@ -66,6 +67,7 @@ typedef Math::Vector3 Vector3i; FunctionsTest::FunctionsTest() { addTests({&FunctionsTest::min, &FunctionsTest::max, + &FunctionsTest::sign, &FunctionsTest::abs, &FunctionsTest::sqrt, &FunctionsTest::clamp, @@ -96,6 +98,13 @@ void FunctionsTest::max() { CORRADE_COMPARE(Math::max(Vector3i(5, -3, 2), Vector3i(9, -5, 18)), Vector3i(9, -3, 18)); } +void FunctionsTest::sign() { + CORRADE_COMPARE(Math::sign(3516), 1); + CORRADE_COMPARE(Math::sign(0.0f), 0.0f); + CORRADE_COMPARE(Math::sign(-3.7), -1.0); + CORRADE_COMPARE(Math::sign(Vector3i(0, -3, 2)), Vector3i(0, -1, 1)); +} + void FunctionsTest::abs() { CORRADE_COMPARE(Math::abs(-5), 5); CORRADE_COMPARE(Math::abs(5), 5);