Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Math.cos() Method Does Not Return 0 When Expected

Using Java on a Windows 7 PC (not sure if that matters) and calling Math.cos() on values that should return 0 (like pi/2) instead returns small values, but small values that, unless I'm misunderstanding, are much greater than 1 ulp off from zero.

Math.cos(Math.PI/2) = 6.123233995736766E-17
Math.ulp(Math.cos(Math.PI/2)) = 1.232595164407831E-32

Is this in fact within 1 ulp and I'm simply confused? And would this be an acceptable wrapper method to resolve this minor inaccuracy?

public static double cos(double a){
    double temp = Math.abs(a % Math.PI);
    if(temp == Math.PI/2)
        return 0;
    return Math.cos(a);
}
like image 832
dimo414 Avatar asked Feb 10 '10 09:02

dimo414


People also ask

What does math Cos do in Java?

cos() returns the trigonometric cosine of an angle. If the argument is NaN or an infinity, then the result returned is NaN. The returned value will be in range [-1, 1].

Is math COS in radians or degrees Java?

The Math. cos() function returns the cosine of a number in radians.


1 Answers

Don't forget that Math.PI/2 is an approximation. It's not going to be exactly pi/2, so the result of cos(Math.PI/2) isn't going to be exactly 0. Math.cos may be returning a pretty accurate version of the cosine of the exact value returned by calculating Math.PI/2.

like image 166
Jon Skeet Avatar answered Sep 24 '22 22:09

Jon Skeet