This week's giveaway is in the Spring forum.We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!See this thread for details.
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of REST with Spring (video course) this week in the Spring forum!

# 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?

...or this another one:

marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

http://www.coderanch.com/t/375505/java/java/Java-Subtraction-Incorrect

"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
sscce.org
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

I agree. Here's the link: http://aspose.com/file-tools

subject: Floating Point Precision