0

I am trying to float operations but i am living this problem.

float a = -3.000002;

float b = -2.999998;

a + b = -6

b - a = 3.33786e-06 giving this value against 0,000004

Emre Kaya
  • 131
  • 5
  • I don't think the title matches the question well. – drescherjm Nov 25 '18 at 03:14
  • Use `double` instead of `float`. – Sid S Nov 25 '18 at 03:18
  • 1
    3.33786e-06 == 0.00000333786 is that not close enough to 0.00004? – Slava Nov 25 '18 at 03:18
  • couldn't reproduce. @Slava The result should be [~0.000003814697266](https://tio.run/##TUtLCsIwFFw3p3jgou0iRSuCtrEncRPSRB40LyFJQRDPHlMX6gzMwHyU91wtku4575DUss4aBLqYgpZ2Yv@ZlYR@YkgJrERqWvZklVmcTBDgCrzvLhvOBjjwY7ff0JuRVTHNw6DcmkCIMi1SFxb7FFEnH7TCiI6aw6n9FgYfev5dblSP7JXzGw "C++ (clang) – Try It Online") – phuclv Nov 25 '18 at 03:21
  • 2
    This is a classic fail-case for floating-point math. -3.000002 can’t be represented exactly, so the stored value is just a little bit off. Same thing for -2.999998 — the stored value is just a little bit off. When you subtract values that are close together you remove the high bits and leave the noise. – Pete Becker Nov 25 '18 at 03:22
  • @SidS — that won’t help. – Pete Becker Nov 25 '18 at 03:23
  • With double on Visual Studio 2017 it prints exactly `4e-06 0.000004000000000` with the code from @phuclv modified to `double r = -2.999998 - -3.000002;` although its `3.9999999996709334e-06` in the debug window. – drescherjm Nov 25 '18 at 03:30
  • @PeteBecker, Sure it will. It'll get you much closer and you can output rounded numbers. – Sid S Nov 25 '18 at 03:40
  • @drescherjm of course it'll be more precise, because double have more precision than float. But you can't get exactly 0.000004 with either float or double because it's impossible to do that in binary floating-point with finite precision. Just print at least 20 digits with double and you'll see that the debugger is correct. Moreover the OP is using float and the above lines are not a [mcve] – phuclv Nov 25 '18 at 04:11
  • @phuclv thanks. I think I understand now. With 20 digits I get this `4e-06 0.00000399999999967093` – drescherjm Nov 25 '18 at 04:35
  • @SidS -- you can **always** round to hide differences in low bits; that doesn't mean that they don't exist. Just like `float`, neither `double` nor `long double` can represent those values exactly; when you **subtract** them you get garbage. Note that I've assumed that the question is not "how can I display this to pretend that I got the value that I expected", but "why is the value not what I expected". – Pete Becker Nov 25 '18 at 16:13

0 Answers0