Simpsons 1/3 rule using n =10 , 100, 1000

i cant get my code to work. im trying to implement the simpsons one-third rule to get the value of the certain function using n =10, 100, 1000. Any Help i would prefer to use the for loops.
%% Parameters
P = 5000; %lb
a= 0; %lower bound
b = 10; %upperbound
n = [10 100 1000]; % step size
f = @(x) P / ((30e6)*(1-0.01*x-0.0005*x.^2)*2*exp(-0.1*x)); %function
%% Simpsons one-third rule
for j = 1:length(n)
h(j) = (b-a)/(n(j));
f_even = 0;
for i = 2:2:n-2 %even
x = a+i *h(j);
f_even = f_even + f(x);
end
f_odd = 0;
for i = 1:2:n-1 %odd
x = a+i *h(j);
f_odd = f_odd + f(x);
end
I(j) = (h(j)/3) * (f(0) + 4* f_odd + 2*f_even +f(10)); %one-third rule
end

2 commentaires

One thing I noticed:
for i = 2:2:n-2 %even
Here, use
for i = 2:2:n(j)-2 %even
instead.
Same with
for i = 1:2:n-1 %odd
Jose Puentes
Jose Puentes le 17 Avr 2020
Thanks it worked !

Connectez-vous pour commenter.

Réponses (0)

Catégories

En savoir plus sur Numerical Integration and Differential Equations dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by