0
#include <iostream>

using namespace std;

int main() {
  float a = 6.2;
  if (a < 6.2) {
    cout << "Yes\n";
  }
  return 0;
}

This code prints yes, Can someone explain why?

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
  • use `if(a < static_cast(6.2))` or `if(a < 6.2f)` – asmmo Sep 14 '20 at 04:49
  • Thank you for explaining, But can you please explain me why it was giving wrong at first? – Asad Ullah Shahid Sep 14 '20 at 04:52
  • 6.2 is double, not a float, hence the comparison includes a truncation and see https://stackoverflow.com/questions/17333/what-is-the-most-effective-way-for-float-and-double-comparison – asmmo Sep 14 '20 at 04:54
  • Simply put, you re comparing `float` to `double`. Each has different precision. Even more simply put. Your float has less precise value of `6.2` than the float, hence it might be smaller since the number actually might be something like `6.200000000006`. – Croolman Sep 14 '20 at 04:55
  • This question throws a `float` vs `double` consideration into the mix (`6.2` is a `double`), but eventually the question comes down to [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) (I'm guessing not a duplicate, though, because of the `float` vs. `double` aspect.) – JaMiT Sep 14 '20 at 05:00
  • 1
    Exactly as it was said above. Also you can declare variable a as `double` and you would not see 'Yes' on cout. – Enrico Sep 14 '20 at 05:01

1 Answers1

3

This code is not required to act any particular way. Any fixed precision representation will sometimes get problems like this wrong.

For example, in six-digit, fixed-precision decimal, 1/3 + 1/3 + 1/3 will not be 1 because 1/3 can only be represented as "0.333333" and adding that three times will give "0.999999". Similarly, 1/3 + 1/3 will not be 2/3 because 2/3 is "0.666667".

Your system can't represent 6.2 exactly just as that one can't represent 1/3 exactly. So you get this kind of weirdness.

Here, the float representation of 62/10 and the double representation of 62/10 aren't equal. Likely, the double representation is closer to the correct value than the float one. The same would be true of 1/3 in decimal. Low-precision might use "0.333333" and high-precision might use "0.333333333333". Those aren't equal. Notice one of them is smaller than the other.

There is no rule that two different approximations of 6.2 must be equal. Why would they have to be?

David Schwartz
  • 179,497
  • 17
  • 214
  • 278