This week's book giveaway is in the Agile forum.
We're giving away four copies of The Software Craftsman and have Sandro Mancuso on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Floating Point Precision Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Software Craftsman this week in the Agile forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Floating Point Precision" Watch "Floating Point Precision" New topic

Floating Point Precision

Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
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

Joined: Aug 31, 2004
Posts: 11343

See this thread...

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
Now I get it. I will make some research about BigDecimal.

Thanks, Marc
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
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.

Mike Gershman
SCJP 1.4, SCWCD in process
Have you tried LearnNowOnline?
subject: Floating Point Precision