'3D vector angle calculation formula returns nan (acos argument bigger than 1 somehow... )

Because of test1 and test2 i know that the issue here is that the argument of acos is larger than 1 and thus i get nAn as result. But what exactly is wrong with my calculation? Vectors are: v1(3,4,0), v2(0,1,0) Expected result for the angle is 36.87°

double Vector::angle(const Vector& input) const
{
    double test1 = sqrt(this->length() * input.length()); //equals 2.23607
    double test2 = this->dotProd(input); //equals 4 

    double result = acos(this->dotProd(input) / sqrt(this->length() * input.length()));
    return result;
}


Solution 1:[1]

But what exactly is wrong with my calculation?

The sqrt at the denominator here:

double result = acos(this->dotProd(input) / sqrt(this->length() * input.length()));

It should be:

double result = std::acos(this->dotProd(input) / (this->length() * input.length()));

You could also infer that from dimentional analysis. If you assume the vector represents, say, the displacement between two points in meters (m):

  • The vector length has unit [m];
  • The dot product has unit [m * m];

So you pass acos a parameter whose dimension is [m], while it should be dimensionless.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1