
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.
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.
You may have the same generic algorithm (written as a template, probably) that you may want to use with different methods of computing errors, for example. For instance: double total_absolute_error = std::inner_product(values.begin(), values.end(), estimates.begin(), std::plus<double>(), absolute_error<double>()); double total_relative_error = std::inner_product(values.begin(), values.end(), estimates.begin(), std::plus<double>(), relative_error<double>()); Anyway the whole point is about comparison, not calculation of the relative error. The comparison strategy is what is most probably going to be passed to algorithms so it's more suitably implemented through function objects. I hope you agree up to this point. Well, now I see the relative_error computation as a policy that customizes a comparison object and also in this case it's more suitably implemented through an object. But enough words, I have uploaded a first implementation of what I have in mind in the boost vault, so you can see what I mean. You will find it in the "math - numerics" folder.
Um, the problem I have with the asymmetric version, is this: which parameter is the "true" value?
The first one ;) Jokes apart, if the programmer knows which is the "true" value (it might happen, really!) he can pass it as the first parameter and use the asymmetric version, otherwise he'll better use the symmetric version.
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.
I know that most programmers will use the symmetric version, but that's not a reason for not providing the asymmetric. The only thing is to choose good names so that everyone is happy and (most importantly) everyone knows what's he doing. Ganesh