• Post Reply Bookmark Topic Watch Topic
  • New Topic

comparing doubles with less than or greater than  RSS feed

 
Chris Zaremba
Ranch Hand
Posts: 54
Eclipse IDE Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand that you shouldn't use equals for comparing two double values but does the same hold true for comparing a double to a literal using less than and greater than?

I have a double variable which holds an angle in degrees calculated using Math.asin and Math.toDegrees etc. If I then compare this to the literal 90 will the result always be true no matter how close a is to but less than 90 and false no matter how close a is to but greater than 90? I'm thinking if a was calculated to be 89.999999998 but the literal 90 is stored internally as 89.999999996;

 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chris Zaremba wrote:I understand that you shouldn't use equals for comparing two double values but does the same hold true for comparing a double to a literal using less than and greater than?
Yes.
campbell@computer_name:~/java$ java DoubleComparison 1.0 0.1 10
d3 < d1: ...
 
Chris Zaremba
Ranch Hand
Posts: 54
Eclipse IDE Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.
 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You see what has happened? Adding 0.1 ten times is one of the better-known pitfalls in floating-point arithmetic. When you use asin, you never quite get back to 90°, so there are bound to be errors because of that imprecision.
 
Chris Zaremba
Ranch Hand
Posts: 54
Eclipse IDE Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes thanks. I knew this was a problem when doing a == b but can now see it's the same issue here. I'm using it for drawing 3d pie segments and have adjusted the drawing method so it doesn't matter if it is +/- a little bit.
 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!