Trapezoidal numerical integration without use of function?
조회 수: 327 (최근 30일)
이전 댓글 표시
I was trying to do trapezoid integration without actually creating a function, but I seem to have done something wrong.
a=0;
b=1;
f=@(x)x.*sin(x);
n=100;
x=linspace(a,b,n+1);
h=(b-a)/n;
qt=sum((h*f((x(1:n)+x(2:n+1)))/2))
This returns 0.4354, when the actual value of the integral is 0.3012. Where am I going wrong with the code?
댓글 수: 2
murat onay
2019년 5월 21일
편집: murat onay
2019년 5월 21일
trapezoid matlab code is here. This code return 0.301180
clc;clear;
a=0;
b=1;
n=100;
h=(b-a)/n;
sum=0;
f=@(x) x.*sin(x);
for i=1:1:n-1
sum= sum + f(a+i*h);
end
result = h/2*(f(a)+f(b)+2*sum);
fprintf('%f',result);
답변 (3개)
John D'Errico
2017년 11월 3일
편집: John D'Errico
2017년 11월 7일
Trapezoidal rule is easy enough. It depends on whether the step is constant or not. The entire point of my response is you need to get the weights correct. If not, then of course your code must fail.
For a constant step size, you need to remember that the weights look like this:
h*[1 2 2 2 2 2 ... 1]/2
So in any interval, we have a trapezoid. The area of a trapezoid is the average of the heights at each end, then multiply by the width.
h*(f(x(i)) + f(x(i+1)))/2
But each trapezoid shares its endpoint with the neighbors. So that gives the first and last points half the weight of the rest. It also gives us a simple way to do trapezoidal rule.
n = 20;
x = linspace(0,pi,n);
dx = x(2) - x(1);
f_x = sin(x);
trapint = (sum(f_x) - (f_x(1) + f_x(end))/2)*dx
trapint =
1.9954
Did we get it correct?
trapz(x,f_x)
ans =
1.9954
Yes. And both agree with the actual result.
syms u
int(sin(u),0,pi)
ans =
2
Could I have done this for unequal spacing? Still easy enough. I'll pick a random spacing here, using a few more points because a random spacing can have some wide places where nothing fell.
n = 50;
x = [0,sort(rand(1,n-2))*pi,pi];
f_x = sin(x);
dx = diff(x);
trapint = dot(dx,(f_x(1:end-1) + f_x(2:end))/2)
trapint =
1.9966
Note that on a function like sin(x) over that interval, trapezoidal rule will tend to underestimate the integral. As you can see, this is exactly what happened, and will always happen for that function, on that interval.
댓글 수: 0
Hiren Rana
2021년 11월 11일
a=0; b=1; n=100; h=(b-a)/n; sum=0; f=@(x) x.*sin(x); for i=1:1:n-1 sum= sum + f(a+i*h);
end result = h/2*(f(a)+f(b)+2*sum); fprintf('%f',result);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Calculus에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!