BLI: Math: Add sign() function

This implement the sign function as simple as possible while giving the
the same result as `signum`.
This commit is contained in:
Clément Foucault 2023-01-13 22:58:45 +01:00
parent 0a7c485b66
commit 8b5d5cbf06
3 changed files with 27 additions and 0 deletions

View File

@ -34,6 +34,11 @@ template<typename T> inline T abs(const T &a)
return std::abs(a);
}
template<typename T> inline T sign(const T &a)
{
return (T(0) < a) - (a < T(0));
}
template<typename T> inline T min(const T &a, const T &b)
{
return std::min(a, b);

View File

@ -70,6 +70,19 @@ template<typename T, int Size> [[nodiscard]] inline VecBase<T, Size> abs(const V
return result;
}
/**
* Returns -1 if \a a is less than 0, 0 if \a a is equal to 0, and +1 if \a a is greater than 0.
*/
template<typename T, int Size>
[[nodiscard]] inline VecBase<T, Size> sign(const VecBase<T, Size> &a)
{
VecBase<T, Size> result;
for (int i = 0; i < Size; i++) {
result[i] = math::sign(a[i]);
}
return result;
}
template<typename T, int Size>
[[nodiscard]] inline VecBase<T, Size> min(const VecBase<T, Size> &a, const VecBase<T, Size> &b)
{

View File

@ -125,4 +125,13 @@ TEST(math_vector, DivideCeil)
EXPECT_FLOAT_EQ(result.z, 0);
}
TEST(math_vector, Sign)
{
const int3 a(-21, 16, 0);
const int3 result = math::sign(a);
EXPECT_FLOAT_EQ(result.x, -1);
EXPECT_FLOAT_EQ(result.y, 1);
EXPECT_FLOAT_EQ(result.z, 0);
}
} // namespace blender::tests