Overloading comparison for double to allow for num

2019-07-02 00:19发布

问题:

In my C++ project I frequently encounter inexact results due to numerical errors. Is it somehow possible to somehow redefine the standard comparison operators (==, <=, >=, <, >) so that they do not compare exactly but within an acceptable error (e.g. 1e-12) ?

(If yes, is it a good idea to do this?)

(Of course one could write comparison functions but people intuitively use the operators.)

回答1:

To overload operators some argument must be user-defined type. The built-in ones are fixed and unchangeable.

But even if you could it would hardly be a good thing. Do yourself a favor, and provide your custom compare "operators" as a set of functions, choosing a name that implies the strategy they use. You can't expect a code reader to know without proper indication that equal means strict or with DBL_EPSILON or 2*DBL_EPSILON or some arbitrary linear or scaled tolerance.



回答2:

You can't overload the operators for standard types (int, float, char, etc)

You could of course declare a type:

class Float
{
    private:
       float f;
    public:
       Float(float v) : f(v) {} 
       ... bunch of other constructors. 
       friend bool operator==(Float &a, Float &b);
       ... more operators here.
       float operator float() { return f; }
};

bool operator==(Float &a, Float &b) { return (fabs(b.f-a.f) < epsilon); }
bool operator==(Float &a, const float &b) { return (fabs(b-a.f) < epsilon); }
       ... several other operator declarations - need on also make operator

(The above code is "as an idea", not tested and perhaps need more work to be "good").

You would of course then need some ugly typedef or macro to replace "float" with "Float" everywhere in the code.



回答3:

No, you cannot overload operators for built-in types. No, changing the semantics of operators is (in general) not a good idea.

You could either:

  • Use comparison-functions (as you suggest yourself).
  • Write a wrapper-class around a double member that has the operators you want.