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);

}

[748 byte] By [NareshBhanotraa] at [2007-11-27 9:21:17]
# 1

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

petes1234a at 2007-7-12 22:15:02 > top of Java-index,Java Essentials,Java Programming...
# 2
Here's a good reference to help you gain a better understanding of floating point arithmetic in java: http://www.concentric.net/~Ttwang/tech/javafloat.htm
Navy_Codera at 2007-7-12 22:15:03 > top of Java-index,Java Essentials,Java Programming...
# 3
http://java.sun.com/developer/JDCTechTips/2003/tt0204.html#2 http://docs.sun.com/source/806-3568/ncg_goldberg.html http://mindprod.com/jgloss/floatingpoint.html
jverda at 2007-7-12 22:15:03 > top of Java-index,Java Essentials,Java Programming...
# 4

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 :-))

_helloWorld_a at 2007-7-12 22:15:03 > top of Java-index,Java Essentials,Java Programming...