Trapezoidal Estimator for the integral

1 次查看(过去 30 天)
I tried here to find a trapezoidal estimate of an area between different intervals(Delta_x); however, errors found are not correct numbers according to others solutions(I checked). I couldnt find my mistake.
Could you look at it?
clc; clear;
f1=@(x) 1+sin(pi*x/100)-sin(pi*x/25);
Area1_actual=integral(f1,0,100);
%%Trapezoidal estimator
c=0;
for Delta_x=[10 5 2.5 1 1/2.5 1/5 1/10];
x = 0:Delta_x:100;
for j=1:(length(x)-1)
Trap_area = Delta_x/2*(f1(x(j))+f1(x(j+1)));
mat_traparea_Tr(j,1) = Trap_area;
end
c=c+1;
Total_area_Tr(c,1) = sum(mat_traparea_Tr);
Error_Tr(c,1) = Total_area_Tr(c,1)-Area1_actual;
end
Delta_x=[10 5 2.5 1 1/2.5 1/5 1/10];
plot(Delta_x,abs(Error_Tr),'b-'); title('Trapezoidal estimator')
xlabel('DeltaX'), ylabel('Errors'); set(gca, 'XDir','reverse')

采纳的回答

David Goodmanson
David Goodmanson 2019-2-24
编辑:David Goodmanson 2019-2-25
Hi Furkan,
case 1: you are calculating Area2 with the trapezoidal approximation, but comparing it to Area1_actual when computing the error. Comparing it to Area2_actual gives much more satisfactory results.
case 2: Area2_actual is computed from 0 to 10, while your trapezoidal calculation is from 1 to 10.
It's true, the devil is in the details.
  7 个评论
John D'Errico
John D'Errico 2019-2-25
It aims to do so. But is incorrect in what it does. I see at least two clear errors.
First, a minor one:
Trap_area_f1=zeros(length(Delta_x)-1,1);
If you would initialize a vector, it makes sense to initialize it to the correct length. Otherwise, preallocation is just a waste of time. Better would be:
Trap_area_f1=zeros(length(x)-1,1);
Of course, the error there is a minor one, since it does not actually create a bug. Just poorly written, inefficient code.
More important?
x=1:Delta_x(i):100;
I might wonder what are the limits of integration? Do you think that might be important? ;-) (Hint.)
You can write lots of scripts that give different answers. Most randomly written scripts would give the wrong result, of course. As I showed rather carefully however, the results I showed in my comment (as generated by the code you wrote after you fixed the error found by David) were actually correct.
FURKAN CEVAHIR
FURKAN CEVAHIR 2019-2-25
So, to make sure, you say that my script with this form in the question is completely true, right?

请先登录,再进行评论。

更多回答(0 个)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by