Home > Mobile >  Angle between vectors returning a Nan
Angle between vectors returning a Nan

Time:02-18

I've been trying to return the angle between vectors, and after several attempts, all that's been printing is "NaN".

public static void displayVector(double v) {
        System.out.print(v);    
}
// magnitude
public static double magnitude(int[] v) {
    double mag = 0;
    for (int i:v) {
        mag  = Math.pow(i, 2);
    }
    mag = Math.sqrt(mag);
    return mag;
}
// angle between vectors
public static double angle(int[] v1, int[] v2) {
    double loopSum = 0;
    double magSum = magnitude(v1)   magnitude(v2);
    for (int i = 0; i < v1.length; i  ) {
        loopSum  = (v1[i]*v2[i]);
    }
    double angle = Math.toDegrees(Math.acos(loopSum / magSum));
    return angle;
}
public static void main(String[] args) {
    int[] A = {2, 5, 7};
    int[] B = {6, 3, 1};
    Helper.displayVector(Helper.angle(A, B));       
}

CodePudding user response:

Your formula is wrong.

The angle is the dot product divided by the product of magnitudes Your code calculates the sum of magnitudes making it smaller than the dot product (loopSum) and therefore calculating acos of a value greater than 1

Change it to

double magProd = magnitude(v1) * magnitude(v2);

Then

double angle = Math.toDegrees(Math.acos(loopSum / magProd));

And it should work like a charm

  • Related