Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Odd behavior with double primitive data type  RSS feed

 
Tom O'Neil
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am encountering very odd behavior trying to add variables of type double. Using JDK 1.4.1, I have the following basic test class:
public class test {
public static void main (String[] args) {
double a = .3;
double b = .6;
double d = a + b;
System.out.println(d);
}
}
Oddly enough, the output of this is:
0.8999999999999999
Does anyone know why this is occurring? All of the variable values are well within the acceptable range for double, so I'm rather stumped as to why I can't get the proper sum.
Tom
kingofthesquids@yahoo.com
 
Norm Miller
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
What you are seeing is Floating point numbers of (theoretically) infinite number of decimal places forced to fit in a fixed length word. The computer, when it converts .3 to binary and then squeezes it into the number of bits available, has to drop a little of its value. Same thing happens to .9 The answer you got is very close, but not exact.
If you use a format statement to round it to a single decimal place, the result would be what you expect.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at this past conversation in the Cattle Drive forum for two very good links on this topic (that are listed later in the conversation).
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!