I must create a program that use trigonometry function.
I know sin(30)=0.5 but when I use Math.sin() I can't get it
Math.sin(30*Math.PI/180)=0.49999999999999994
What's the problem?
Thank you
Stefano Buscherini
A few of the other posters have commented that you need to understand
the limits of floating point arithmetic. Note that there are at least
three ways that comes into play in this problem.
Mathematically we know
sin(pi/6) = 1/2
exactly. However Math.PI is an approximation of the value of PI so
30*Math.PI/180 is an approximation of pi/6. So when we take the sine
we are taking the sine of a number that's a little different from the
number we really wanted. That's one source of error. You can see
this most easily by looking at the value
of
Math.sin(Math.PI)
It is not 0 but a value of about 10^-16. This is not an error in the
computation of the sine, it represents the difference between Java's
approximation to pi and the true value. This source of error is
sometimes a little surprising to users.
The second source of error is in the arithmetic within the
parentheses. Anytime you operate on floating point numbers, and
especially if you are dividing, you are likely to get an answer that
is not exact. For division this is easy to see. You cannot write
10./3 in any finite decimal representation. While a computer users
binary rather than decimal, the same issue arises. If we combine this
with the first error it's possible that there is a number that Java
could represent that is closer to the value pi/6 than the value you
will actually get using 60*Math.PI/180.
The last source is in the computation of the sine itself. Java
permits (but does not require except in strictmath) mathematical
functions to have very small errors in the calculations. If the
correct answer is x, the result of the computation can be either x, or
the smallest number the computer can distinguish from x that is larger
than x, or the largest number the computer can distinguish from x that
is smaller than x. In practice this means that the answer is within
about 10^-16 x of the true value.
Regards,
Tom McGlynn