-5

In a special case I have the number 0.068404 in two variables (these change while the program is running so I don't know what is in it).

When I'm substracting by itself, it gives the infinite or precisely a number at the power -9. All booleans operations give me a wrong result.

Any ideas?

intboolstring
  • 6,891
  • 5
  • 30
  • 44
Render
  • 41
  • 6
  • This is just the floating point representation very near zero. It's not infinite, it's just very small. That "-9" you refer to is `10^-9` and it's the scientific notation of the number. – Brian Cain Mar 31 '16 at 01:44
  • You shouldn't compare floating point numbers for equality. Floating point is [inexact](https://isocpp.org/wiki/faq/newbie#floating-point-arith) – PaulMcKenzie Mar 31 '16 at 01:46
  • But it should gives 0, it's weird ! When i don't multiply it by a number between 0 and 1 (to change the vector length) it works – Render Mar 31 '16 at 01:48
  • @Render -- It should not "give 0". Again, floating point is inexact. See the link I posted. – PaulMcKenzie Mar 31 '16 at 01:49
  • It probably should not give 0. But if you included a minimal complete example I could help illustrate exactly why. – Brian Cain Mar 31 '16 at 01:49
  • @paulmckenzie, floating point numbers are not inexact, they are deterministic and well-understood. The challenge is precision when converting from base 2 to base 10 and visa-versa. – nicomp Mar 31 '16 at 01:56
  • @nicomp When I say inexact, I mean that the representation of a decimal fraction cannot be represented exactly by a binary number, unless the decimal fraction is the sum of inverse powers of 2. – PaulMcKenzie Mar 31 '16 at 02:03

1 Answers1

3

You are likely experiencing floating point rounding issues, a very common problem that has been dealt with time and time again. Consider the following program:

float a, b, c;

cin >> a;
b = a;
a = a*3;
a = a/3;
c = a - b;
cout << c << " " << (c == 0) << endl;

By all rights you should get a print out of 0 1, but when you try it here. You get:

2.48353e-09 0

This is because floating point numbers cannot represent every base 10 number, so rounding errors make straight comparisons a bad idea. You should always use an epsilon, ie:

abs(a - b) < eps

where eps is something like 1e-6.

Here you can find many more examples.

Community
  • 1
  • 1
Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175