0
votes

I started coding a couple of days ago and made a simple trig calculator. It uses degrees and gives out degrees as the answer for most values, except some.

For example. If I want the answer to sin(90), it gives it to me, but if I want the answer to sin(180), it gives me an incorrect one.

Here's the code for the sin function

Scanner input = new Scanner(System.in);
System.out.println ("sin, cos, or tan?");
String trig = input.next();

if (trig.equals ("sin")) {
System.out.println ("input sin value in degrees");
Scanner angle = new Scanner(System.in);

double a,b;

a = (angle.nextDouble());
b = Math.sin(Math.toRadians(a));
System.out.println("Answer: "+ (b) );

It gives me answers like 1.2246467991473532E-16 for the following angles: 180, 360, 540, 720 etc.

This also happens for the cos and tan functions (it only happens when the tan functions are undefined though, so I can understand that one).

1
wolframalpha.com/input/?i=sin(180) and 1.2246467991473532E-16 is "almost" 0, some reading: floating-point-gui.deuser180100
Why are you using two Scanners? One is enough.user207421
The result of Math.toRadians(180) is not exactly equal to the mathematical constant π, and therefore Math.sin(Math.toRadians(180) is not exactly 0.njuffa

1 Answers

2
votes

1.2246467991473532E-16 is rather small number, not so far from zero. While working with float or double almost always you don't need to compare to exact number like

a == 0

but use something like

Math.abs(a - 0) < epsilon

where epsilon is required accuracy, e.g. 1E-10