clstaudt
clstaudt

Reputation: 22448

Overloading comparison for double to allow for numerical error

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.)

Upvotes: 4

Views: 2883

Answers (3)

Balog Pal
Balog Pal

Reputation: 17183

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.

Upvotes: 4

Mats Petersson
Mats Petersson

Reputation: 129464

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.

Upvotes: 3

Kleist
Kleist

Reputation: 7985

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.

Upvotes: 2

Related Questions