0

In c++17, let's consider the following.

float num1 = 3.1005;
float num2 = 1.0005, num3 = 2.1000;
float res = num2 + num3;

Then, I would imagine res = 3.1005 and consequently res == num1 -> TRUE. But that is not the result I get.

More confusingly,

cout << res; --> output: 3.1005
cout << (res == num1); --> output: false

Furthermore,

cout << fixed;
cout.precision(3);
cout << res; --> output: 3.100
cout << num1; --> output: 3.101

Can someone, please, explain to me why this is happening.

San Kim
  • 177
  • 1
  • 8
  • 1
    Choose an acceptable difference in fraction and if difference is less than it, consider them equal. Float comparison is not safe. – no more sigsegv Mar 18 '22 at 06:52
  • 4
    See [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). And consider to print the numbers with a higher precision, e.g. `cout.prescision(20)` to see the _actual_ values, not just the rounded ones. Default precision is 6 significant digits I believe, so you always get rounded output, unless you specify otherwise. – Lukas-T Mar 18 '22 at 06:52
  • 1
    If you print with `std::cout << std::fixed << std::setprecision(22) << num1 << '\n' << num2 << '\n' << num3 << '\n' << res;` you get the following results: `num1=3.1005001068115234375000`, `num2=1.0004999637603759765625`, `num3=2.0999999046325683593750`, `res=3.1004998683929443359375` – Lukas-T Mar 18 '22 at 06:58
  • Ah, yes. I get the same result. So, that probs explains why `res = 3.1004..` is not rounded up. Thanks for the comments guys. – San Kim Mar 18 '22 at 07:00

0 Answers0