Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Precision of float and double

 
John Stark
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12185
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
John Stark
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's what I was basically thinking.

Thanks,

John
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic