> Hi all,
>
> Sorry if this question has been already asked in the past (I bet so).
> I would appreciate if you could point me in the right direction.
>
> I do not generally compare doubles because I am well aware of the
> round-off errors that make such a comparison meaningless.
>
> However, I am trying to write my program in a test-driven way, so I'd
> like to write a tester that checks that the result of a specific
> calculation is actually zero.
[...]
> For now, in MathComparer::equalsZero(), I am using a (wrong - I know)
> direct == comparison between the argument passed in and 0.0, but I'd
> like to replace it with the appropriate comparison using an epsilon.
>
> Am I correct in thinking that the epsilon should actually be chosen
> depending on the current calculation and the accuracy I am expecting
> from it?
Yes. As a trivial example, adding-subtracting an unbounded amount of
floating-point numbers can result in arbitrily large shifts from the
correct value.
However, most probably your algorithm has a limited number of floating-
point operations, so it ought to be possible to calculate the maximum
possible error. Alas, finding this can be well more complicated than the
original algorithm so it seems an overkill for a test function (you might
need to write a test for the test, etc). Probably the best approach is to
use some kind of epsilon estimated by gut feeling, but not totally
arbitrary.
>
> I can see, for example, that the solve() method most of the times
> returns 0.0 but at times something like 6e-12 (which is absolutely
> sensible, given the imprecise nature of floating-pint types).
6e-12 seems actually pretty big error unless the numbers in your tests
themselves are pretty large. The zero which is output from your test
function is most probably the result of subtracting two large numbers.
You should actually compare the relative difference of those numbers,
e.g. divide them by each other and if the result differs from 1.0 more
than a few epsilons (std::numeric_limits<double>::epsilon()) then your
algorithm might be either wrong or numerically unstable (the latter is
worse). The exact value of "few" above would be based on gut feeling ;-)
hth
Paavo