Click here to Skip to main content
14,388,220 members
Rate this:
Please Sign up or sign in to vote.
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

1 solution

Rate this:
Please Sign up or sign in to vote.

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).

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

—SA
   
v6
Comments
[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

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100