Results 1 to 4 of 4
Thread: Why java cant do sum properly
- 05-15-2010, 06:48 AM #1
Member
- 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.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 #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,407
- Blog Entries
- 7
- Rep Power
- 17
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 #3
Member
- Join Date
- May 2010
- Posts
- 2
- Rep Power
- 0
I get it
Thanks for help :)
- 05-26-2010, 07:40 AM #4
Member
- 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: 09-16-2009, 05:45 AM -
Using accessors properly
By LifeWithJava in forum New To JavaReplies: 2Last Post: 12-23-2008, 02:49 PM -
Eclipse Documentation does not work properly.
By krawetko in forum EclipseReplies: 0Last Post: 10-05-2008, 10:06 AM -
Log4j not working properly....
By prakash_dev in forum Advanced JavaReplies: 0Last Post: 03-17-2008, 12:13 PM -
how to properly express adding...
By paul in forum New To JavaReplies: 1Last Post: 08-07-2007, 05:08 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks