I want to make ‘==’ operator use approximate comparison in my program: float values x and y are equal (==) if
abs(x-y)/(0.5(x+y)) < 0.001
What’s a good way to do that? Given that float is a built-in type, I don’t think I can redefine the == operator, can I?
Note that I would like to use other features of float, the only thing that I’d like to change is the equality operator.
EDIT:
Thank you for the answers, and I understand your arguments about readability and other issues.
That said, I really would prefer, if possible, to actually keep using the regular float type, instead of having a new class or a new comparison function. Is it even possible to redefine == operator for regular floats?
My reasons are::
(a) everyone using the program I’m writing wants the floats to be compared this way
(b) there’s no way in the world anyone would ever want to use the default == for floats.. Why is it even in the language???
(c) I dislike extra words in the code; obviously using the existing float results in no changes in the code whatsoever
EDIT 2.
Now that I know I can’t overload the == operator for float, I have to change my question. It will become so different that I’ll make a new one at custom comparison for built-in containers
Your definition has two problems:
Missing an
*Will attempt to divide by zero if
x + y == 0.0(which covers a possibly frequent casex == y == 0.0)Try this instead:
Edit: Note the use of
<=instead of<… needed to make thex == y == 0.0case work properly.I wouldn’t try to override
==Edit 2: You wrote:
No way? Suppose you have a function that returns a float, and you have a brainwave about an algorithm that would produce the same answers faster and/or more elegantly; how do you test it?