2

To be more exact, does std::equal_to<float>()(float a,float b) or std::equal_to<double>()(double a,double b) does the somewhat better float equality like abs(diff) < EPSILON or just a==b?

Alex
  • 467
  • 4
  • 13
  • I'd never trust one arbitrary float to exactly equal another. The best plan is that they're within some acceptable mathematical distance, as you note there. – tadman Dec 18 '14 at 19:33
  • 1
    Note that using [a good reference](http://en.cppreference.com/w/cpp/utility/functional/equal_to) would answer this question for you. *"Function object for performing comparisons. Unless specialised, invokes `operator==` on type T."* – cdhowie Dec 18 '14 at 19:35
  • 1
    The problem is that your statement of the 'right' way to compare floating point values paints with too broad a brush. Sometimes that's the right way, sometimes 'epsilon' has to be chosen based on careful numerical analysis of the exact code producing the floating point values, somtimes exact == equality is correct. It depends on what exactly you're doing. – bames53 Dec 18 '14 at 19:38
  • Note that your definition of "correct float equality" is actually incorrect in nearly all cases! This comparision would be only meaningful for floating point values close to 1.0 and even then it is most likely incorrect: when you need to extend the range of values to be considered equal you'll need a proper error analysis. The resulting term _may_ involve `EPSILON` but just `EPSILON` is rather unlikely to be correct. – Dietmar Kühl Dec 18 '14 at 20:03
  • @DietmarKühl @bames53 I understand that. I just thought that it would have a more accurate equality check than just `==` – Alex Dec 18 '14 at 20:07
  • Why would an equality operator consider values which are not equal (clearly `x != x + epsilon` for `epsilon != 0`)? The one thing which would neat to get fixed in an equality function is that `x == x` may yield `false` for objects with a floating point type but `std::equal_to` doesn't do that either. – Dietmar Kühl Dec 18 '14 at 20:11

1 Answers1

7

std::equal_to uses == to perform the comparison. If you want to compare with a tolerance, you'll have to write that yourself. (Or use a library.)

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • 2
    @Nawaz I don't think you're allowed to specialize standard library templates on built-in types. – Brian Bi Dec 18 '14 at 19:35
  • 4
    @Nawaz *results in undefined behavior unless the declaration depends on a user-defined name of external linkage* – Praetorian Dec 18 '14 at 19:39
  • 3
    The relevant quote for C++11 is *"A program may add a template specialization for any standard library template to namespace `std` only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited."* (17.6.4.2.1 [namespace.std]) – cdhowie Dec 18 '14 at 19:41
  • After some quick testing, I found this to be true. – Alex Dec 18 '14 at 20:02