Results 1 to 4 of 4
Thread: Why java cant do sum properly
 05152010, 06:48 AM #1Member
 Join Date
 May 2010
 Posts
 2
 Rep Power
 0
Why java cant do sum properly
I wondering why java goes wrong when compute simple sum, such as 0.80.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);
}
}
 05152010, 09:03 AM #2
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 14,322
 Blog Entries
 7
 Rep Power
 25
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
 05152010, 11:04 AM #3Member
 Join Date
 May 2010
 Posts
 2
 Rep Power
 0
I get it
Thanks for help :)
 05262010, 07:40 AM #4Member
 Join Date
 May 2010
 Posts
 5
 Rep Power
 0
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)."
Similar Threads

how to getText() properly?
By javamula in forum New To JavaReplies: 12Last Post: 09162009, 05:45 AM 
Using accessors properly
By LifeWithJava in forum New To JavaReplies: 2Last Post: 12232008, 03:49 PM 
Eclipse Documentation does not work properly.
By krawetko in forum EclipseReplies: 0Last Post: 10052008, 10:06 AM 
Log4j not working properly....
By prakash_dev in forum Advanced JavaReplies: 0Last Post: 03172008, 01:13 PM 
how to properly express adding...
By paul in forum New To JavaReplies: 1Last Post: 08072007, 05:08 AM
Bookmarks