Help needed with errors in trapezoidal formula for integration

1 回表示 (過去 30 日間)
David Oshidero
David Oshidero 2017 年 11 月 21 日
編集済み: Walter Roberson 2017 年 11 月 21 日
I have gotten my code working to an extent however the code takes forever to work and I was hoping someone could help me check if this is the best way to do it as the error needs to be less than 0.001%. Thanks for any contributions anyone can give.
function trapezoidal(N)
clc
%%Limits & sub-intervals
a = 0;
b = 0.449933;
if nargin == 1
n = N;
else
n = 100;
end
fprintf('\n Limits[%g,%g] \n',a,b);
% h = (b-a)/n;
%%Integral Aproximation (Composite Trapezoidal Rule)
integral = 0;
for j=1:n
ri=2^j;
h = (b-a)/ri;
for i = 1:ri
r_left = a+(i-1)*h;
r_right = a+i*h;
% Functions
f_left = f(r_left);
f_right = f(r_right);
% Integral
integral = integral+(h/2)*(f_left+f_right);
end
% Print the approximation to the value fo the intragral
%%Calculating Relative Error
if j > 1
errorrel = ((integral-integralo)*100/integral);
%%Loop Termination
if abs(errorrel) < 0.001
break
end
fprintf('\nMidpoint approximation to integral using %g subintervals is %g with Error %g\n',ri,integral,errorrel);
end
integralo = integral;
end
end
function [f_value] = f(r)
%%Variables
k = 2;
n = 0.85;
pgrad = -80;
R = 0.449933;
%%Equation
f_value = 2*pi*((-pgrad/(2*k))^(1/n))*((R^(1+1/n)-r^(1+1/n))/(1+1/n))*r;
end

回答 (0 件)

カテゴリ

Help Center および File ExchangeCalculus についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by