# Why java cant do sum properly

• 05-15-2010, 06:48 AM
thetimwu
Why java cant do sum properly
I wondering why java goes wrong when compute simple sum, such as 0.8-0.7, I get 0.100000024 ?
Here is my code:

public class Test {

private float[] x = {0.5F,0.3F,-0.7F};
private float[] y = {1F,1F,1.0F};
private float z=0.0f;
private float[] temp = new float[3];
private float sum ;

public static void main(String[] args) {
Test myTest = new Test();
myTest.countNum();
}

public void countNum() {
for(int i=0;i<x.length;i++){
//for(int j=0;j<y.length;j++)
// sum = 0.0F;
sum = x[i]*y[i];
temp[i] = sum;
System.out.println(temp[i]);
}
System.out.println(z);
for(int j=0;j<3;j++){
z += temp[j];
System.out.println("print the sum of temp: " + z);
}
z=0.8f+(-0.7f);
System.out.println("print the sum of temp: " + z);

}
}
• 05-15-2010, 09:03 AM
JosAH
The IEEE754 floating point number system (that's what Java uses) represents floating point numbers as sums of the numbers 1/2, 1/4, 1/8, 1/16 ... Try to pick a subset of numbers from this set, add those numbers and try to make the sum 1/10 (decimal). You can't, Java can't and nobody can.

The number 1/10 can not be represented exactly in the IEEE754 number system. Compare this with the number 1/3 (decimal) as a decimal expansion: it can't be represented exactly either (you need an infinite number of 3s).

Use the DecimalFormat class to get the visual representation of those numbers right.

kind regards,

Jos
• 05-15-2010, 11:04 AM
thetimwu
I get it
Thanks for help :)
• 05-26-2010, 07:40 AM
shaycorl
Josh thanks a lot buddy just made a print out of your explanation for future use i am damn sure i am gonna need it one day.
"The number 1/10 can not be represented exactly in the IEEE754 number system. Compare this with the number 1/3 (decimal) as a decimal expansion: it can't be represented exactly either (you need an infinite number of 3s)."