[Haskell-cafe] Re: Defaulting to Rational [was: Number overflow]

apfelmus apfelmus at quantentunnel.de
Thu Jul 12 10:58:31 EDT 2007


Bryan O'Sullivan wrote:
> apfelmus wrote:
> 
>> In a sense, the instances of Eq and Ord for floating point numbers are
>> wrong. What about rolling new classes for approximate equality and
>> ordering?
>>
>>   class ApproxEq a where
>>     (≈) :: a -> a -> Bool -- almost equal to
> 
> The problems with this approach are generally worse than those with Eq,
> whose shortcomings are at least well defined and widely understood.

What I wanted to do is to capture common patterns

  x - y >= epsilon
  abs (x - y) <= epsilon

for comparing floating point numbers in nice functions

  x >> y = x - y >= epsilon
  x ≈  y = abs (x - y) <= epsilon

This way, one could simply use >> and ≈ with floating point numbers and
be assured without much thinking that the resulting code is more or less
robust. But I guess that there are too many variants of these patterns
and that thinking is always required.

> You need to choose an epsilon of the right magnitude for the numbers
> you're working with, and the epsilon is likely to be domain-specific.

In case the epsilon is problem specific but static, one can use phantom
types.

> Also, since these aren't equivalence relations, ApproxEq has the
> weird property that a ≈ b and b ≈ c does not imply a ≈ c;
> ApproxOrd suffers from the same problem.

Yes. But that's intended and the very nature of robustly comparing
Doubles and Floats :(


Regards,
apfelmus



More information about the Haskell-Cafe mailing list