Boost logo

Boost :

From: John Maddock (john_at_[hidden])
Date: 2006-04-25 05:40:25


>> BTW I notice in other messages that folks have been talking about a
>> function > object for this, but.... what use would that be for? At
>> present I can't see anything simpler and easier to use than just a
>> free function:
>>
>> template <class T>
>> T relative_error(T, T);
>>
>
> Interesting. The other posters are talking about function objects
> because I started the discussion with them. The main reasons I did
> that
> is that function objects are more suitable to be passed as arguments
> to algorithms because the compiler can inline them (more) easily.
> Having
> free functions could be a nice addition but they shouldn't replace
> function objects entirely, IMHO.

I realise why they're used, but I'm struggling to think of an example where
one would pass a function object that returns relative error to another
function: in other words I'm looking for your motivation.

> BTW, there is a subtle but important fact to consider: a function like
> relative_error() is usually understood by mathematicians as a tool to
> compute the error of an estimated value w.r.t. an expected value. In
> particular, the two parameters have different roles and the algorithm
> is asymmetric:

Yep, I realise that.

> However our goal is to determine whether two values are simply
> near to each other. A programmer therefore could (and should) expect
> the algorithm to be symmetric in the two parameters.
>
> Of course, we could please both worlds by providing relative_error as
> defined above, plus this:
>
> template <class T>
> T relative_error_symmetric(T x, T y)
> { return std::max(relative_error(x, y), relative_error(y, x)); }
>
> and then defining the comparison function object in terms of the
> latter.
> What do you think?

Um, the problem I have with the asymmetric version, is this: which parameter
is the "true" value?

Or to put it another way, it's way too easy to screw up and pass the
parameters the wrong way around, and no amount of testing you do will ever
detect that mistake (especially if you're getting spurious test passes as a
result of your mistake, unlikely I realise but possible). That's why I
always test my code with a symmetrical version, just called
"relative_error".
It's not quite what a mathematician would expect, but from a programming
perspective it's more robust.

Just my 2c again.

John.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk