c++floating-point

C++ Unexpected behaviour in floating-point operation


So, I writed some code:

#include <iostream>
#include <cmath>

int main() {

    int a,b,n;
    std::cin >> a >> b >> n;
    double xi[n];
    double yi[n];
    double h = (b - a + 0.0) / n + 0.0;
    
    for (int i = 0; i <= n; ++i) { //filling the arrays
        xi[i] = a + (h*i);
        yi[i] = xi[i]*xi[i]*std::acos(0.9*xi[i]); //the 
    }
    for (int i = 0; i <= 5; ++i)  { //displaying first 5 elements of the arrays
        std::cout << "x" << i << ": " << xi[i] << "\n";
        std::cout << "y" << i << ": " << yi[i] << "\n\n";
    }
    return 0;
}

If you try to run it with a = 0, b = 1 and n = 10 (later I discovered that any number divisible by 10 gives similar results), then instead of x0 = 0, you will see that x0 = 0.451027.

I tried forcefully assigning to xi[0] its supposed value

if (i == 0) {
    xi[i] = a;
}

Now x0 still equals to this 0.451027 nonsense, but if in the first case the value of y0 was correct (0), with forced assigning it is 9.2684e-315, which is almost correct if you think, but still is not 0. static_cast was also helpless in solving this mystery.

It feels surreal and yet it happens run after run. Is it possible to fix it?


Solution

  • Array bounds: your loop for (int i = 0; i <= n; ++i) is going to cause you all sorts of trouble because you're accessing out of bounds on xi and yi. arrays in c++ are zero-indexed, so you should loop from 0 to n-1. Like this: for (int i = 0; i < n; ++i).

    This fixes the issue.