Browse Source

Added Vector::lengthSquared() function.

The name is a little bit misleading, but it is for more efficient vector
length comparisons.
vectorfields
Vladimír Vondruš 14 years ago
parent
commit
2be1ff3763
  1. 4
      src/Math/Test/VectorTest.cpp
  2. 1
      src/Math/Test/VectorTest.h
  3. 18
      src/Math/Vector.h

4
src/Math/Test/VectorTest.cpp

@ -93,6 +93,10 @@ void VectorTest::length() {
QCOMPARE(Vector4(1.0f, 2.0f, 3.0f, 4.0f).length(), 5.4772256f);
}
void VectorTest::lengthSquared() {
QCOMPARE(Vector4(1.0f, 2.0f, 3.0f, 4.0f).lengthSquared(), 30.0f);
}
void VectorTest::normalized() {
QVERIFY(Vector4(1.0f, 1.0f, 1.0f, 1.0f).normalized() == Vector4(0.5f, 0.5f, 0.5f, 0.5f));
}

1
src/Math/Test/VectorTest.h

@ -30,6 +30,7 @@ class VectorTest: public QObject {
void multiplyDivide();
void addSubstract();
void length();
void lengthSquared();
void normalized();
void product();
void angle();

18
src/Math/Vector.h

@ -218,11 +218,27 @@ template<class T, size_t size> class Vector {
return out;
}
/** @brief %Vector length */
/**
* @brief %Vector length
*
* @see lengthSquared()
*/
inline T length() const {
return sqrt(dot(*this, *this));
}
/**
* @brief %Vector length squared
*
* More efficient than length() for comparing vector length with
* other values, because it doesn't compute the square root, just the
* dot product: @f$ a \cdot a < length \cdot length @f$ is faster
* than @f$ \sqrt{a \cdot a} < length @f$.
*/
inline T lengthSquared() const {
return dot(*this, *this);
}
/** @brief Normalized vector (of length 1) */
inline Vector<T, size> normalized() const {
return *this/length();

Loading…
Cancel
Save