It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Precision of float and double Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Precision of float and double" Watch "Precision of float and double" New topic

Precision of float and double

John Stark
Ranch Hand

Joined: Jul 19, 2011
Posts: 185
One question in Enthuware is about precision of floats and doubles. It turnes out that

prints 'true'. When I change it to

it still prints 'true'.

prints 'false'. I don't really understand this behavior.

Another question is: Obviously in Java it is OK to compare floats or doubles directly:

In C you don't do that because 1.0 might not be exactly 1.0. You do something like:

So you check whether the difference between the number is sufficiently small.

Why can I compare doubles directly in Java? Can anybody explain?


fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11952

I'm not sure about the details about why it works in some of your cases and not others, but i wouldn't ever count on it working.

Most high-level languages follow the IEEE standard on floats. I've never read it, but it basically defines how they should work.

I would not bet the farm on your examples still evaluating true/false the same with other computations, so I think your idea of comparing within a certain delta is probably the right way to go in Java, too.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
John Stark
Ranch Hand

Joined: Jul 19, 2011
Posts: 185
That's what I was basically thinking.


I agree. Here's the link:
subject: Precision of float and double
jQuery in Action, 3rd edition