Re: Adding two float values got strange result
Pietro Marrone wrote:
On 17 Apr, 11:50, Pietro Marrone <pietromarr...@gmail.com> wrote:
Hi, thie is my simple test case:
public class Main {
public static void main(String[] args) {
float a = 123.76f;
float b = 52.0f;
System.out.println(a + b);
System.out.println((float) a + b);
System.out.println((float) a + (float) b);
System.out.println((float) (a + b));
}
}
The results for all four System.out is the same, guess what?:
175.01001
Cuold anyone explein me why, at least a refer to rules explaining what
happens?
Regards
Another wrong test case:
package it.test;
public class Main {
public static void main(String[] args) {
float a = (float)123.76;
float b = (float)52.0;
System.out.println(a + b);
System.out.println((float) a + b);
System.out.println((float) a + (float) b);
System.out.println((float) (a + b));
}
}
gives 175.76001, but unfortunetly neither this result is correct.
The result you report for this program matches the answer Andrew and I
got for the first program.
Java float and double each represent numbers in binary floating point.
Java float has, effectively, 24 significant bits, the equivalent of
about 7.2 decimal digits. You should expect rounding error in the 8th
significant decimal digit.
The rules are in the JLS, see
http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3
the following section, and the sections they reference.
IEEE 32 bit float is almost always the wrong data type to use. It gives
up a lot of accuracy for halving the space required compared to double.
If you should be using a binary floating point type at all, you should
normally use double. The exception is if you are storing a large number
of values with low accuracy requirements, and have done the numerical
analysis to convince yourself that float is precise enough.
If you need the behavior you seem to expect, exact representation and
addition of decimal fractions, consider using BigDecimal.
Patricia