-1

I'm trying to get some calculation but when x equal zero it output some strange number. What might the problem be?

 #include <iostream> 
    #include <math.h>  
    using namespace std;
    void main() 
    { 
        const int N = 100;  
        int i;  
        double x, h, a = -1.0, b = 1.0, y[N+1];  
        h = (b - a)/N; //h=0.02
        for (i = 0, x = a; i <= N; i++, x += h)  
        { 
            if (x == 0) // When x is 0

            {
                cout << x << '\t' << "0.00" << endl;
                continue;
            }
            y[i] = exp(-x*x);  
            cout << x << '\t' << y[i] << endl; 
        }


    }

Problem part of output

Vladimir
  • 31
  • 4
  • 3
    Don't use == to compare floating point numbers – JGroven Mar 07 '17 at 04:10
  • 1
    6.17562e-016 is not a "strange number". This is very small value. Another way to represent this value is 0.000000000000000617562. But it is not so convenient. – Ilya Mar 07 '17 at 04:18

1 Answers1

1

This is likely caused by comparing a double value to 0. You should always compare double values to a tolerance, i.e.,

if (abs(x)  < 0.0001) 

instead of

if (x == 0)

You can use any minimum acceptable value instead of 0.0001. See this answer for more details.

Community
  • 1
  • 1
tjcertified
  • 694
  • 7
  • 18
  • Or simply `if ( abs(x) < 0.0001)`. – R Sahu Mar 07 '17 at 04:25
  • Why did you write `0 - x` instead of `x` – M.M Mar 07 '17 at 04:42
  • Good comments. I fixed this. – tjcertified Mar 07 '17 at 11:03
  • Did you actually read the question you linked to? Because the first question explains why `<0.0001` is a bad idea. There's no natural scale to floating-point numbers, 0.0001 is just as small as 100000000. (E.g. 0.0001 kilometer is just as small as 10000000 nanometer) – MSalters Mar 07 '17 at 14:31
  • The question was linked for the OP to consider, and to explain the idea of an epsilon value. OP would need to consider the appropriate epsilon for their application, and include all conversions and caveats necessary. Of course I read the linked question. The first answer is a great post for anyone looking at this solution to think about when considering epsilon-based comparison, so I linked it here for the OP to weigh. I do not presume to know everything about the desired usage of this function, so I directed the reader to a more complete discussion of the problem. – tjcertified Mar 07 '17 at 17:07