0

I am working on a calculator with a GUI in Java. The project is done, however the trigonometric functions do not work properly. This is the method for the cos function:

public void actionPerformed(ActionEvent evt) {
input = Double.valueOf(Display.getText());
ans = Math.cos(Math.toRadians(input));
Display.setText(String.valueOf(ans));
} 

Where "Display" is the text area. The problem is that the functions return inaccurate values. For example, when I enter 90 and click the cos button, the number 6.123233995736766E-17 is returned. The sin and tan buttons are also inaccurate in a similar manner (I can explain further if necessary). Where is the code going wrong, and how can I solve this

  • 3
    Possible duplicate of [sin, cos, tan and rounding error](http://stackoverflow.com/questions/1527588/sin-cos-tan-and-rounding-error) – Arc676 Jan 17 '16 at 09:07
  • Also see http://stackoverflow.com/questions/2235689/java-math-cos-method-does-not-return-0-when-expected?rq=1 – Arc676 Jan 17 '16 at 09:08
  • [eps](https://en.wikipedia.org/wiki/Machine_epsilon) in your system is probably 2.22e-16. The result is actually pretty accurate. – Manos Nikolaidis Jan 17 '16 at 14:45

1 Answers1

2

The value returned by cos is not inaccurate. When you input 90, and convert it to radian using the method Math.toRadians, the result is not exactly pi/2, and hence when you pass this non-exact value to cos it gives a non-exact value. Peek here to hear from the legend :-)

As for your situation, you need to round the result of cos. Take a look here

You could do something like this:

public void actionPerformed(ActionEvent evt) {
    input = Double.valueOf(Display.getText());
    ans = Math.cos(Math.toRadians(input));
    Display.setText(String.format("%.6f", ans));
} 
Community
  • 1
  • 1
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90