I’m doing a lot of floating point operations in my application, and I’m aware that floating point operations are not 100% accurate which is fine but when it comes to printing the result I have yet to find a way to format it properly.
for example
0.1 + 0.1 = 0.19999999999999999999999
Math.sin(Math.PI) = 1.2246E16 instead of 0
and stuff like 1.000000000000000001
I’m looking for a general way to take those results and get the proper rounded value (in a String form)
so that
0.1 + 0.1 = 0.19999999999999999999999 -> 0.2 this one requires rounding up
Math.sin(Math.PI) = 1.2246E16 -> 0
and stuff like 1.000000000000000001 -> 1 ; while this one requires rounding down
I’d also like to avoid losing data in cases like when the result is
1.1234567891234567 or 1.33333333333333 in those cases the result should remain the same.
If you want to avoid using formatting, you can round the result to a fixed precision before printing it and use the fact that Java will do a small amount of rounding to hide representation error.
e.g. To 6 decimal places
The result of
round()and1e6can be represented exactly. Additionally “IEEE 754 requires correct rounding: that is, the rounded result is as if infinitely precise arithmetic was used to compute the value and then rounded” The only error left is the representation error as it takes the nearest representable value. Java’s toString() assumes that when you have a double which has a nearest representable value of a shorter decimal, that is what you want to see.e.g. The actual value for 0.1 is
prints
but when Double.toString() is passed this value, it determines that 0.1 would be converted to this double and so this is what it should be displayed.
BTW In Java 6 there is a bug where it doesn’t use the minimum number of digits.
in Java 6 prints
and in Java 7 prints
I often use printf if performance is not critical and if it is, I use a custom routine to write the double to a direct ByteBuffer to a fixed precision (effectively rounding it) This is faster as it doesn’t create any objects.
In that case, don’t round the results until you need to display them.