• Post Reply Bookmark Topic Watch Topic
  • New Topic

Strange Addition results  RSS feed

 
Kevin Crays
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was playing around the other day and got some very strange floating point addition results. I have others, which now seem to produce the correct 9.3, but did not the other day (nothing changed, AFAIK, but I rebooted at some point).

anyway, these are the equations and the results. I think of any way that the first and last equation can have those results.


double dd;
dd = (float) (4.1d + 5.2d) //= 9.300000190734863
dd = (double) (4.1d + 5.2d) //= 9.3
dd = 4.1d + 5.2f //= 9.299999809265136
 
Edwin Keeton
Ranch Hand
Posts: 214
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Floating-point arithmetic often provides inaccurate results. Google on floating-point arithmetic and you will find several thorough discussions of the issue.

Basically, the problem occurs as a result of representing decimal fractions in binary. Any fraction that is not a multiple of a negative power of two (.5, .25, .75, .125, etc.) cannot be represented accurately in a binary system. The approximation is usually close enough that after rounding, we're not aware of the discrepancy.

The BigDecimal class will solve the problem for you if you need absolute accuracy without spurious rounding errors.
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Some fractions cannot be represented in decimal format due to its infinite notation. Like 1/3 which is 0.33333333...

The same happens with some binary numbers. When you conver 9.3 to binary, it is 1001.01001100110011001...

Hence, some operations may not yield an exact result. That's why you should use BigDecimal insteand of primitive floating point arithmethic if you expect to do operations with a more accurate result (like those related with money or astronomy).
[ April 28, 2006: Message edited by: Edwin Dalorzo ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See item #23 in this FAQ.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!