|
Boost : |
From: Alberto Ganesh Barbati (abarbati_at_[hidden])
Date: 2006-04-24 16:38:05
John Maddock ha scritto:
>
> 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.
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:
template <class T>
T relative_error(T value, T estimate)
{ return abs((value - estimate) / value); } // asymmetric!
(see, for example http://en.wikipedia.org/wiki/Relative_error)
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?
Ganesh
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk