0

I'm trying to make a function to compute an integral using Composite trapezoidal rule in numerical methods. But the thing is, when I'm going to check whether the input data points are equally spaced, There is a error. Because of the floating point numbers. Here's my code

    function answer = composite_trapezoidal (X, Y)
lx = length(X);
ly = length(Y);
h = X(2) - X(1);
validity = 1;
series_sum = 0;
answer = 0;

if (lx ~= ly)
    fprintf('Error ! Dimensions Of Data Point Vectors Doesn''t Match\n');
else
    for i = 1:lx - 1
        hTmp = X(i + 1) - X(i);
        if (hTmp ~= h)
            validity = 0;
            fprintf('Invalid Data Points. Data Must Be Equally Spaced !\n');
            break;
        end
    end
end

if (validity == 1)
    for i = 2:lx - 1
        series_sum = series_sum + Y(i);
    end
    answer = (h / 2) * (2 * series_sum + Y(1) + Y(ly));
end

consider the input x = linspace(0, 2, 7); Then the function terminates with "data points are not equally spaced". But the thing is they were computed using linspace. I can understand the problem. Points are 0, 0.3333333, 0.6666667, etc. So they aren't equally spaced when rounding up. But the problem is Can we fix this ?

ThisaruG
  • 3,222
  • 7
  • 38
  • 60

2 Answers2

3

Checking equality with rounded numbers is usually unstable. You could try using an acceptable tolerance such as abs(hTmp-h)< 10^-4 or even better use a relative tolerance with abs(hTmp-h)/abs(hTmp) < 10^-2

emiliojorge
  • 146
  • 8
1

Consider using a tolerance in your comparison, because floating operations are exact within some accuracy (see this page). Typically use eps for that, it is common to use a muliple of this value for tolerance.

Bentoy13
  • 4,886
  • 1
  • 20
  • 33