Search This Blog

Thursday, April 28, 2011

Precision math in Java



Faith has it that I work on some statistical software currently. One thing required when you work on statistical software is data computation precision. Precision on floating point numbers with Java is not so straightforward. While I understand this because of the fact that you squeeze infinite numbers of decimals in finite number of places (classical example of representing in floating point arithmetic 1/3), at the end of the day I just wanted to do 19.99+18.47==38.46.
But you don't always get what you wish for. So, instead of 38.46, Java gave me back 38.4599999994. This is, obviously, not equal to 38.46. To make the equality work, I just used the very nice and friendly BigDecimal class from the java.math package, like this:
BigDecimal.valueOf(19.99d).
         add(BigDecimal.valueOf(18.47d)).doubleValue()
After this, I was the happy owner of a working addition on doubles. Alas, the boss was just bored of my solution (quote: "Just make it work!!").
Check the java.math package for other stuff:http://java.sun.com/j2se/1.5.0/docs/api/java/math/package-summary.html

No comments:

Post a Comment