File APIs for Java Developers Manipulate DOC, XLS, PPT, PDF and many others from your application. http://aspose.com/file-tools
Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login Today (12/10) is CodeRanch Day in Manning's Countdown to 2014. Use discount code crdotd14 all month for 50% off every deal. CodeRanch Day is 50% off our pick of books: Secrets of the JavaScript Ninja; The Well-Grounded Java Developer; Java 8 Lambdas in Action; HTML5 in Action; The Responsive Web; and Java Persistence with Hibernate

# comparing doubles with less than or greater than

Chris Zaremba
Ranch Hand

Joined: Nov 22, 2010
Posts: 54

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;

SCJA, OCPJP, OCMJD
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 34600

13
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

Joined: Nov 22, 2010
Posts: 54

Thanks.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 34600

13
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

Joined: Nov 22, 2010
Posts: 54

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
Sheriff

Joined: Oct 13, 2005
Posts: 34600

13
You're welcome

I agree. Here's the link: http://aspose.com/file-tools

subject: comparing doubles with less than or greater than