I need to take my trapezoid rule code and adjust it keeping the same format to Simpson rule
조회 수: 2 (최근 30일)
이전 댓글 표시
I need to take my trapezoid rule code and adjust it keeping the same format to Simpson rule. I am just no sure how to get this done. I have tried this and keep getting errors. Here is my trapezoid code. Thank You so much! function s = myTrap(f,a,b,n) x = linspace(a,b,n+1); %for n trapezoids, use n+1 points h = (b-a)/n; s = (f(a)+f(b))/2; %initialize sum %trap sum for i = 2:n s = s + f(x(i)); end s = s*h; %multiply sum by h when f= @(x)sqrt(1+x^3) from 1-4 with 20 traps I get 12.875041 for simpson the same function 1-4 should output 12.871490
댓글 수: 0
답변 (1개)
Paras Gupta
2024년 6월 21일
Hello,
I understand that you want to adjust your trapezoid rule code to implement Simpson's rule while keeping the same format. Please refer to the following code to achieve the same in MATLAB:
f = @(x) sqrt(1 + x^3);
a = 1;
b = 4;
n = 20;
result = mySimpson(f, a, b, n);
fprintf('Result: %.6f\n', result);
function s = mySimpson(f, a, b, n)
if mod(n, 2) ~= 0
error('n must be even for Simpson''s rule');
end
x = linspace(a, b, n+1); % for n intervals, use n+1 points
h = (b - a) / n;
s = f(a) + f(b); % initialize sum with f(a) and f(b)
% Simpson's rule sum
for i = 2:2:n
s = s + 4 * f(x(i));
end
for i = 3:2:n-1
s = s + 2 * f(x(i));
end
s = s * (h / 3); % multiply sum by h/3
end
Hope this helps.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Numerical Integration and Differential Equations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!