addition of double variables
This code should return 4.53 but is returning 4.52999999. Can anyone help please.
publicstaticvoid main(String args[])
{
double doubleArray[]={1.11,1.13,1.14,1.15};
double doubleSum = 0.0;
for (int i=0; i<4; i++)
{
doubleSum = doubleSum + doubleArray[i];
}
System.out.println(doubleSum);
}
Welcome to floating point arithmetic. This is a good time to learn that doubles and all floating point numbers are usually not exact representations of what you think they should be. This is not a Java issue, but a general floating point issue. You should read a good tutorial on this subject.
Here's one:
http://www.ibm.com/developerworks/java/library/j-jtp0114/
Look in particular at the section labled Rounding errors.
Good luck!
ps: I see that this is your first post here. I want to unofficially welcome you to this forum. Also, thank you for using code tags in your first post. This is quite unusual and a pleasant surprise.
Message was edited by:
petes1234
Also you may want to look at BigDecimal if you want to get the results back you were expecting.
Take a look here:
http://www.ibm.com/developerworks/java/library/j-jtp0114/
Note that BigDecimal is immutable and each calculation produces a new BigDecimal Object and this can lead to a big overhead if you are doing something really intensive (which you probably are not :-))