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

(+) operator  RSS feed

 
Subhash Nambiar
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All
I was just wandering by a very abnormal output from the simple summation of double values in JAVA
Like i tried these examples
double d1 = .11;
double d2 = 1.53;
//Result : 1.6400000000000001
double d1 = .11f; //same value with f appended
double d2 = 1.53f; //same value with f appended
//Result : 1.639999970793724
double d1 = .11;
double d2 = 1.43;
//Result : 1.54
Though 1st one is almost correct but still not accurate and i couldnt able to trace the reason for this behaviour.And there is no fix pattern it is following.
Could anyone suggest what cld be the problem and where i shld look for finding the possible reason for it.
If i want to know how/which algorithm java do for (+) operator, where cld i find the same.
Thanks in advance
Subhash
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is that many decimal numbers can't be represented exactly in binary formats such as that used for double primitives, no matter how many bits are used. Your result is not abnormal, just unexpected.
You might look at the java.math.BigDecimal class.
Bill
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!