I have been given the task of using java to produce a Sin table, however I seem to get some very weird results for some values of the input. I am using the below
System.out.println("| sin(" + currentPoint + ") = " + Math.sin(Math.toRadians(currentPoint)));
Where (int) currentPoint is a value in degrees (eg 90)
These are results I find weird
| sin(360) = -2.4492935982947064E-16
| sin(180) = 1.2246467991473532E-16
| sin(150) = 0.49999999999999994
| sin(120) = 0.8660254037844387
Expecting
sin(360) = 0
sin(180) = 0
sin(150) = 0.5
sin(120) = 0.866025404
Am I missing something?
You’re dealing with floating point numbers, looking for exact answers isn’t going to work for all values. Take a look at
What Every Computer Scientist Should Know About Floating-Point Arithmetic. You want your tests to be equivalent to your expectations within some delta. Note that the answers you’re getting are pretty close. It’s expressing values in bits that’s biting you.
From the link: