| Author |
Precision of float and double
|
John Stark
Ranch Hand
Joined: Jul 19, 2011
Posts: 165
|
|
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: 9944
|
|
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.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
John Stark
Ranch Hand
Joined: Jul 19, 2011
Posts: 165
|
|
That's what I was basically thinking.
Thanks,
John
|
 |
 |
|
|
subject: Precision of float and double
|
|
|