From 43f5f0695601b961f2aac9aca0983f5781c545a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vladim=C3=ADr=20Vondru=C5=A1?= Date: Tue, 28 Jan 2020 17:32:21 +0100 Subject: [PATCH] Math: avoid warnings when calling length() on an integer Vector. Also update the docs to hint the result may be imprecise on integer types, and suggest Manhattan length as well. --- doc/snippets/MagnumMath.cpp | 13 +++++++++++++ src/Magnum/Math/Vector.h | 17 +++++++++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/doc/snippets/MagnumMath.cpp b/doc/snippets/MagnumMath.cpp index 350e465fe..9091292b2 100644 --- a/doc/snippets/MagnumMath.cpp +++ b/doc/snippets/MagnumMath.cpp @@ -1130,6 +1130,19 @@ Vector4i integral{floatingPoint}; // {1, 2, -15, 7} /* [Vector-conversion] */ } +{ +/* [Vector-length-integer] */ +Vector2i a{25, -1}; +Float length = Vector2{a}.length(); // ~25.099 +/* [Vector-length-integer] */ +static_cast(length); + +/* [Vector-length-manhattan] */ +Int manhattanLength = Math::abs(a).sum(); // 26 +/* [Vector-length-manhattan] */ +static_cast(manhattanLength); +} + { Vector2 vec; Float length{}; diff --git a/src/Magnum/Math/Vector.h b/src/Magnum/Math/Vector.h index 7aa391b8f..d4a02bc57 100644 --- a/src/Magnum/Math/Vector.h +++ b/src/Magnum/Math/Vector.h @@ -501,11 +501,24 @@ template class Vector { * other values. @f[ * |\boldsymbol a| = \sqrt{\boldsymbol a \cdot \boldsymbol a} * @f] + * + * For integral types the result may be imprecise, to get a + * floating-point value of desired precision, cast to a floating-point + * vector first: + * + * @snippet MagnumMath.cpp Vector-length-integer + * + * A [Manhattan length](https://en.wikipedia.org/wiki/Taxicab_geometry) + * might be more suitable than @ref length() in certain cases where the + * square root is undesirable --- it's a sum of absolute values: + * + * @snippet MagnumMath.cpp Vector-length-manhattan + * * @see @ref lengthInverted(), @ref Math::sqrt(), @ref normalized(), * @ref resized() * @todo something like std::hypot() for possibly better precision? */ - T length() const { return std::sqrt(dot()); } + T length() const { return T(std::sqrt(dot())); } /** * @brief Inverse vector length @@ -606,7 +619,7 @@ template class Vector { /** * @brief Sum of values in the vector * - * @see @ref operator+() + * @see @ref operator+(), @ref length() */ T sum() const;