1

I am posting this question because I tried searching for similar questions in Stack Overflow but couldn't find one (If there is one, please provide me wit the link).

According to basic trigonometry, the cosine of 90 degrees is 0. However, it seems like this is not the case in Java (Is this also true for sine and other trigonometric functions?). I'm really confused about this and I am hoping someone could provide me with an easy-to-understand explanation. Thank you.

public static void main ( String args [] ) {
    double radians = Math.toRadians ( 90 );
    System.out.println ( Math.cos ( radians ) );
}

I should be getting 0, but what I get when I run this code is 6.123233995736766E-17.

Sam
  • 77
  • 7
  • 6
    6.1E-17 is really close to 0. This is because of floating point calculations which are not precise. – svz Aug 02 '13 at 10:44
  • Floating point numbers tend to not be entirely accurate for irrational numbers. That answer is probably nearly exact for the rounded pi/2 created by toRadians(). 0.00000000000000006 is really close to 0. You'll probably need a different library for exact answers. – Paul Aug 02 '13 at 10:48
  • double radians = Math.toRadians ( 90 ); System.out.println ( Math.round(Math.cos ( radians ) )); – Nitesh Verma Aug 02 '13 at 10:48
  • `Math.toRadians ( 90 )` does not convert 90 degrees to pi/2 radians exactly. That would take infinite precision. Instead a value _nearest_ to pi/2 is saved in `radians`. It is this value given to `cos()`. The cosine of that nearest-to-pi/2 value is `6.123...E-17`. – chux - Reinstate Monica Aug 04 '13 at 06:04

1 Answers1

-1

6.123233995736766E-17 is probably about as close as you can get to 0 with a double...

See Comparing a double against zero for more info

Community
  • 1
  • 1
John3136
  • 28,809
  • 4
  • 51
  • 69