Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 837
clstaudt Avatar asked Oct 15 '25 04:10

clstaudt


1 Answers

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.

like image 105
Balog Pal Avatar answered Oct 17 '25 17:10

Balog Pal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!