Hellong
Hellong

Reputation: 21

(Java) Strange NaN in a double while using Math.acos

I have a strange problem on my code: I want to compute an arc-cosinus, and I use the Math.acos for that. But when I try to compute it, it sometimes returns NaN (I said "sometimes" because it occurs 1/10 time with the same value).

And the worst is that:

double angle = Math.acos((v.xdest-v.xi)/Math.sqrt(Math.pow(v.xdest-v.xi,2)+Math.pow(v.ydest-v.yi,2)));
System.out.println(angle);
    /* 
    Some code
    */
System.out.println(Math.acos((v.xdest-v.xi)/Math.sqrt(Math.pow(v.xdest-v.xi,2)+Math.pow(v.ydest-v.yi,2))));

When I run this code, I get:

NaN 
2.620575634136091

Even if it is the same calculation!

And if I run:

double angle = Math.acos((v.xdest-v.xi)/Math.sqrt(Math.pow(v.xdest-v.xi,2)+Math.pow(v.ydest-v.yi,2)));
System.out.println(angle);
System.out.println(Math.acos((v.xdest-v.xi)/Math.sqrt(Math.pow(v.xdest-v.xi,2)+Math.pow(v.ydest-v.yi,2))));
        /* 
        Some code
        */

I get

NaN
NaN

It looks like the code between the two calculations makes it possible. But this code doesn't modify anything.

I don't know what to do.

(xdest-xi and ydest-yi are always the same, so they are not the source of my problem)

Upvotes: 2

Views: 2466

Answers (1)

tikhonos
tikhonos

Reputation: 602

double Math.acos(double v) should return NaN if v is NaN or if Math.abs(v) is greater than 1. If you are trying to calculate an angle between two vectors, you should use formulae like these:

double angleBetweenVectors(Vect v1, Vect v2) {
    double cos = scalarProduct(v1, v2) / (length(v1) * length(v2));
    double acos = Math.acos(cos);
    return Math.toDegrees(acos);
}

double scalarProduct(Vect v1, Vect v2) {
    double x1 = v1.xdest - v1.xi;
    double x2 = v2.xdest - v2.xi;
    double y1 = v1.ydest - v1.yi;
    double y2 = v2.ydest - v2.yi;
    return x1*x2 + y1*y2;
}

double length(Vect v) {
    double x = v.xdest - v.xi;
    double y = v.ydest - v.yi;
    return Math.sqrt(x*x + y*y);
}

Upvotes: 3

Related Questions