Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Floating Point Precision

 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have read in the Java Language Specification 2nd Edition that floating point operations might be imprecise. Let's this code snippet:



I get this output:

Square Root: 1.4142135623730951
Second Power: 2.0000000000000004
Not Equal


So, what should I do when working with floating-point numbers to make sure the calculations are appropriate. Above all in the scientific and financial applications?

Any idea?

See also these snippets that I took from JLS:



...or this another one:

 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See this thread...

http://www.coderanch.com/t/375505/java/java/Java-Subtraction-Incorrect
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now I get it. I will make some research about BigDecimal.

Thanks, Marc
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I did some scientific programming years ago. The two ways I checked for equality were to compare the absolute value of the difference to a small number and (more accurately) to subtract 1.0 from the quotient and compare the absolute value to a small number.

For financial applications, double is for homework. Real applications use BigDecimal.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic