0

I was just experimenting with methods in my Java class and I followed exactly what the book has as an example. However when i take the cosine of pi / 2, I get a value of 6.123233995736766E-17 which is clearly incorrect (The answer should be 0). Why am I getting this value? Is there something wrong with my code?

import java.util.*;

public class JavaPractice {
  public static void main(String[] args) {
    double num = Math.cos(Math.PI / 2);
    System.out.print(num);
  }
}
Ryan Foster
  • 103
  • 9

1 Answers1

4

The exact value of PI cannot be stored (as it is irrational and goes on forever), so Java uses an approximation. Thus, PI/2 isn't exact either and so you are taking the cosine of a value that is almost PI/2. You will notice that the answer that you get it very close to 0. Nothing is wrong with your code.

sadiela
  • 106
  • 7
  • 1
    To go further on this answer. Imagine `delta = Pi - Math.Pi` (with `Pi` the true value) What you actually compute is `cos((Pi - delta)/2) = sin(delta/2) ~ delta/2` – kvantour Jan 04 '19 at 11:12