14,388,220 members
Rate this:
See more:
Hello,

Am trying to create simple while loop until my variable will be 0.
So am created a
```do
{
x = x + 0.001;
cout << x0 << endl;
} while (SOME_CALCULATION != 0);```

Everything works great until my loop reach 0 then i getting 7.63278e-017 instead of 0.

Loop example:

```<br />
result: -0.003<br />
result: -0.002<br />
result: -0.001<br />
result: 7.63278e-017<br />
result: 0.001<br />
result: 0.002<br />
result: 0.003<br />```
Posted

Rate this:

Solution 1

You should just understand that floating-point types do not represent real numbers (in real numbers, a number generally represents infinite amount of information; this is something which cannot be represented in a finite-state machine like a computer :-)); they represent some approximation.

As I remember, in the most well-known book by Donald E. Knuth, The Art of Computer Programming, Knuth warned the readers against using equality comparison ('==', in C/C++/C# terms) on floating-point types. Instead, you can use `fabs(value1 - value2) < someSmallNumber;` where `someSmallNumber` is defined by a particular problem, and `fabs` is this:
http://www.cplusplus.com/reference/cmath/fabs[^].

In your case, it would be `while (fabs(SOME_CALCULATION) < someSmallNumber)`.

http://en.wikipedia.org/wiki/The_Art_of_Computer_Programming[^],
http://en.wikipedia.org/wiki/Donald_Knuth[^].

—SA
v6
[no name] 24-Apr-14 14:32pm

+5. What I remember is, he not just warned from such comparison he wrote something like "never do it". Regards, Bruno
Sergey Alexandrovich Kryukov 24-Apr-14 15:58pm

Thank you, Bruno.

I cannot tell exact wording by Knuth; it could be "never do it", which is still a kind of warning. Well, stronger warning. Clear enough for me to never do it. :-)

—SA