simpsons 1/3 rule calculating error

10 ビュー (過去 30 日間)
Giovanna Girotto
Giovanna Girotto 2022 年 11 月 26 日
回答済み: John D'Errico 2022 年 11 月 26 日
i have this code that calculates the integral, but i am having trouble implementing the code part where i evaluate the error and make a graph between the error and the number of segments
function I = simp13(func,x0,xn,n,varargin)
if nargin < 3, error('São necessários pelo menos 3 argumentos de entrada');end
if ~(xn>x0), error('O limite superior deve ser maior que o limite inferior'); end
if nargin < 4 || isempty(n), n = 100; end
x = 0;
h = (xn-x0)/n;
s = func(x0,varargin{:});
for i = 1:(n-1)
x = x+h;
if mod(i,2) == 1
s = s + 4*func(x,varargin{:});
s = s + 2*func(x,varargin{:});
s = s + func(xn,varargin{:});
I = ((xn-x0)*s)/(3*n);


John D'Errico
John D'Errico 2022 年 11 月 26 日
Before you worry about how to plot things, and compute the error, should you worry if your code is correct at all? Gosh, that just seems logical. :)
You pass in x0 and xn. They are clearly the lower and upper limits of your integral, based on the code.
Then you evaluate func at x0, and at the end, at xn. Still ok.
Then you define x, starting at ZERO. Then you increment x, from the point, by increments of h.
Do you see the problem?
What if you were to call this code for an integral that does not have a lower limit of zero?
Therefore your code is not even correct. I've not bothered to evaluate the rest of the code.
How do you compute the error? You must know the true value of the integral, since it is you who are providing func. Perform that integral symbolically. Then outside of this code, use a loop. Compute the integral once for each number of segments. Save the result. Compute the difference between thetrue value and your estimate. Plot. Where is the problem?

その他の回答 (0 件)


Find more on Numerical Integration and Differential Equations in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!

Translated by