I’m trying to make a maths computer game, and have been getting frustated with floating-point arithmetic imprecision. For example, I do some calculations on a number and I always end up with something like 8.99999999999978 instead of 9.0.
I never understood why the hell that happened but I found this great blog article about how it works. Here it is if you’re interested: http://funcall.blogspot.com/2007/06/how-floating-point-works.html
I was thinking of using BigDecimal instead of doubles, but I don’t think they’ll solve my troubles because the floating point arithmetic will still be inexact, but to a lesser extent. By the way, here’s an interesting thread about BigDecimal performance:
http://forum.java.sun.com/thread.jspa?threadID=5119298&start=0&tstart=0
I modified the original benchmark to get rid of the string concatenation and parsing:
public static void test(){
System.out.println("Test: BigDecimal performance");
final long iterations = 10000000;
long t = System.currentTimeMillis();
double d = 123.456;
for (int i = 0; i < iterations; i++) {
final double b = d * System.currentTimeMillis() * System.currentTimeMillis();
}
System.out.println("double: "+(System.currentTimeMillis() - t));
t = System.currentTimeMillis();
BigDecimal bd = new BigDecimal("123.456");
for (int i = 0; i < iterations; i++) {
final BigDecimal b = bd.multiply(new BigDecimal(System.currentTimeMillis())).multiply(new BigDecimal(System.currentTimeMillis()));
}
System.out.println("java.math.BigDecimal: "+(System.currentTimeMillis() - t));
}
These are my results, after running that test method once to warm it up:
Java HotSpot(TM) Client VM 11.0-b11
Test: BigDecimal performance
double: 797
java.math.BigDecimal: 9250
So BigDecimal is more than 10 times slower in java 6.

