wood burning stoves 2.0*
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Precision of float and double" Watch "Precision of float and double" New topic
Author

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'.
But

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?

Thanks,

John
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11161
    
  16

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.

Thanks,

John
 
Don't get me started about those stupid light bulbs.
 
subject: Precision of float and double
 
Similar Threads
Floating Confusion
Question from JQ+
floating point math
Doubt
'if' with float &double