-2

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:

result: -0.003
result: -0.002
result: -0.001
result: 7.63278e-017
result: 0.001
result: 0.002
result: 0.003
Fr33c3l
  • 165
  • 1
  • 1
  • 11

4 Answers4

3

Do something like that:

    double epsilon = 0.00001; 
    do
    {
        x = x + 0.001;
        cout << x0 << endl;
    } while (abs(SOME_CALCULATION) > epsilon);
0x90
  • 39,472
  • 36
  • 165
  • 245
2

You might want to consider rewriting this as

x = -3;

do
  {
  x = x + 1;
  cout << x0 / 1000 << endl;
  } while (SOME_CALCULATION != 0);

SOME_CALCULATION will need to be adjusted for the fact that x is now an integer rather than a fractional floating point value - perhaps replicating the x0 / 1000 within the calculation would work.

Share and enjoy.

1

Some real numbers cannot be represented exactly in floating point (for example, 1.0/3.0). As a result, rounding errors are introduced, and can accumulate in surprising ways. Check out this link for more information.

Depending on your algorithm, a simple workaround could be to check for <=0 rather than ==0. In general, if you find yourself checking equivalency of a floating point value, you should think twice and ensure that all possible values are exactly representable using the type specified.

MooseBoys
  • 6,641
  • 1
  • 19
  • 43
0

Workaround: Used long or int variables and convert to double before output:

#include <iostream>

using namespace std;

main()
{
    int x=-3;
    do
    {
        x = x + 1;
        cout << ((double)x)/1000 << endl;
    } while (x < 4);
}

Output:

-0.002
-0.001
0
0.001
0.002
0.003
0.004