0
    double d = 0.0;
    if (d == 0.0) {
        cout << "yes" << endl;
    } else {
        cout << "nope" << endl;
    }

If I have a double of d, and when I want to compare it with 0, should not I write like if (d < 1e-6)? (if the eplison of 1e-6 is enough) But when I build codes like if (d == 0) in whatever complier, it always output "yes". https://godbolt.org/z/Tcvf87P6n why would that be? So is if (d == 0) the right version when comparing between two doubles?

f1msch
  • 509
  • 2
  • 12
  • 1
    it depends what you want to do. Do you need to check for equality or for approximate equality? Blindly applying only one when the others is needed will lead to problems. – 463035818_is_not_an_ai Jul 18 '23 at 08:40
  • you are actually asking two distinct questions. A) why does comparing with 0 work as expected? B) which one should I use? The duplicate is for A. B depends. – 463035818_is_not_an_ai Jul 18 '23 at 08:44
  • If your double variable has an exact value then `d == 0.0` is fine. If your double variable does not have an exact value (i.e. the value it contains has some rounding error) then `abs(d) < 1e-6` might be better. The difficulty is knowing the difference. – john Jul 18 '23 at 09:22
  • Note that `d < 1e-6` is not an equality test, but maybe you just made a typo. – john Jul 18 '23 at 09:24
  • 1
    You might be interested in reading [this post](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition), comparing floating point numbers can be a bit of a can of worms when you really start looking into it. Things are not the same when comparing small and large numbers for example. – Pepijn Kramer Jul 18 '23 at 10:30
  • you need to be aware of the implications. For example `a == b` and `b == c` implies that `a == c`, but `abs(a-b) < eps` and `abs(b-c) < eps` does not imply `abs(a-c) < eps`. – 463035818_is_not_an_ai Jul 18 '23 at 11:09
  • 1
    Exact comparisons between doubles is okay if the values are known (or expected) to be exact. Floating-point numbers are sometimes maligned because some people expect them to behave like (in the mathematical sense) real numbers. If the comparison needs "wiggle room", Knuth provided the algorithms to do those comparisons, q.v.: https://stackoverflow.com/a/253874/4641116 – Eljay Jul 18 '23 at 11:31

0 Answers0