Sign in to follow this  
stphung

[java] Trig Methods in Java

Recommended Posts

In Java, when I make the call Math.sin(2*Math.PI) the value returned is -2.4492935982947064E-16 when intuitively it seems like it should be 0. Is there something clean that I could do to solve this problem?

Share this post


Link to post
Share on other sites
Expanding the given number results in -0.00000000000000024492935982947064 (if I counted correctly) what is numerically (w.r.t. FP numbers) close to 0. Problems like this are immanent since a number is stored with a limited resolution only. E.g. PI needs an unlimited amount of digits to the displayed numerically correct. The question is, however, whether or not this is really a problem in the given context. If you really need greater precision then go with java.math.BigDecimal or something alike, but remember that its computations are more expensive (and still may yield in not perfect results if using e.g. trig functions). If you only want to display the result to the user then perhaps simply restrict the output to a couple of decimal digits, e.g. 4 or 5.

EDIT: When used in rotation matrices that are concatenated over a long running animation, numerical imprecision is known to yield in violation of rotation matrix conditions. In cases like these you need to perform some re-normalizations. If numbers are compared then use epsilons to overcome it, e.g.
Math.abs( number - should ) < EPSILON
instead of
number == should
where EPSILON is a small constant.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this