[plt-scheme] ProfessorJ, ==, and double

From: Carl Eastlund (carl.eastlund at gmail.com)
Date: Tue Jan 25 14:34:50 EST 2005

On Tue, 25 Jan 2005 14:02:34 -0500, Don Blaheta <dblaheta at knox.edu> wrote:
> Quoth Carl Eastlund:
> > The == operator doesn't operate on type double in ProfessorJ: Beginner
> Because floating point numbers shouldn't be tested for equality, due to
> numeric error.  Consider:
>   > double x = (1.0 / 6) * 10000;
>   > double y = 10000.0 / 6;
>   > x
>   1666.6666666666665
>   > y
>   1666.6666666666667

Fair enough.  I've seen this reasoning before, I just wasn't sure it
was the reason in use here.

> Now, there are situations once you know what you're doing, when you know
> that numeric error can't arise, that you can make use of ==, but Java
> beginners really shouldn't use those.  The correct way to test equality
> on doubles is
>   > double epsilon = 0.0001;
>   > Math.abs (x - y) < epsilon
>   true

I'm very wary of the claim that this is "correct".  For very very
large values - the distance in meters between galaxies, for instance -
this epsilon is woefully small and this might as well be the == test. 
For very very small values - the distance in meters between electrons,
for instance - this epsilon is woefully large and this might as well
be the constant true.  I think floating-point comparison is a trickier
issue than this, and not one necessarily solvable by making freshman
students declare or use a constant epsilon.

> It's really the same reason that you can't use == on objects in Beginner
> ProfJ: it doesn't mean what they might intuitively expect it to mean, so
> you don't want them using it until they understand its problems.

That's true.  I just think it's unfortunate that some very natural
examples become very difficult to test until this issue is addressed.

> What "earliest examples" in HtDCH are you referring to?

I was referring to the incarnation of the HtDCH course being taught
currently at Northeastern, and not to any particular examples in the
test.  We've been writing methods like distanceToZero and
priceWithTax, and we've needed a way to compare double-valued results
for test cases.  This worked its way into our labs before comparison
techniques worked its way into our lectures.


Posted on the users mailing list.