A piece of the program, which should build a graph by points. N - number of nodes. a, b - start and end point. h is a step. I found a problem, so I reduced the code to a training one. The bottom line is that when N> = 100, not N elements are entered into the array, but N + 1, and because of this, an error occurs. What's the matter?

double a = -5, b = 5, h; double N = 50; double *m; int i = 0; h = (b - a)/N; m = new double[N]; for (double x = a; x < b; x += h) { m[i] = i; cout << i << " " << m[i] << endl; i++; } cout << "и i конеч = " << i << endl; 

N = 50

N = 50

N = 100 or more

enter image description here

    3 answers 3

    Rewrite your code like this:

     cout << i << " " << m[i] << " x = " << setprecision(20) << setw(20) << x << endl; 

    and with N = 100 you will see that the value of x with i==100 turns out to be 4.9999999999999973355 , not 5 , but the value h = 0.10000000000000000555 . Roughly speaking, a floating-point number is an approximation using the sum of fractions of the form 1/2^n , so it is clear that not every fractional number can be represented by a double type variable exactly ...

    In floating-point calculations, any comparison should always be considered approximate , and where you work with integer data by nature - the same array indices - do not replace them with floating-point numbers. Use, so to speak, natural types for your objects.

      It was not necessary to do a loop on a real variable. Rewrite to integer.

       for(size_t i=0;i<N;++i) { m[i] = i; cout << i << " " << m[i] << endl; } 

      Explanation

      Any calculations with real numbers are performed with an error, since not all numbers can be represented as a finite fraction with a denominator of 2.

         for (double x=a, int i=0; i<N; x += h, i++){ m[i] = i; cout << i << " " << m[i] << endl; }