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 ?