Skip to main content
gamedev.net
🔒 Locked

[java] Trig Methods in Java

Started by stphung Apr 5, 2007 at 2:58 AM 1 replies 1.1k views
Original Post
stphung
stphung
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?
haegarr
haegarr
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.