Write a MATLAB code integral_0^1 cos (x^2)dx using the composite trapezoid rule
ID: 3768394 • Letter: W
Question
Write a MATLAB code integral_0^1 cos (x^2)dx using the composite trapezoid rule and one to approximate the integral using the composite Simpson's rule, with equally-spaced nodes. The number of intervals n = 1 / h should be an input to each code. Turn in listings of your codes. Do a convergence study to verify the second-order accuracy of. the composite trapezoid rule and the fourth-order accuracy of the composite Simpson's rule; that is, run your code with several different h values and make a table showing the error E_h with each value of h and the ratios E_h/h^4 for the composite trapezoid rule and E_h/h^4 for the composite Simpson's rule. These ratios should be nearly constant for small values of h. You can determine the error in your computed integral by comparing your results with those of MATLAB routine quad. To learn about routine quad type help quad in MATLAB. When you run quad, ask for a high level of accuracy, say, q = quad('cos(x.-2), 0, 1, [1.e-12 1.e-12]) where the last argument [1.e-12 1.e-12] indicate answer that is accurate to 10^-2 in both a relative and an absolute sense. [Note that when you use routine quad you must define a function, either inline or in a separate file, that evaluates the integrand cos(x^2) of values of x; hence you need to write cos(x.-2), instead of cos(x-2).]Explanation / Answer
function integral = cmptrap(a,b,n,f)
h = (b-a)/n;
x = [a+h:h:b-h];
integral = h/2*(2*sum(feval(f,x))+feval(f,a)+feval(f,b));
Run with
cmptrap(1,2,4,'f')
where ’f’ is the name of the function definition file
function y = f(t)
y = t.*log(t); % pay attention to the dot
function integral = cmpsimp(a,b,n,f)
h = (b-a)/n;
xi0 = feval('f',a)+feval('f',b);
xi1 = 0;
xi2 = 0;
for i = 1:n-1
x = a+i*h;
if mod(i,2) == 0
xi2 = xi2+feval('f',x);
else
xi1 = xi1+feval('f',x);
end
end
xi = h*(xi0+2*xi2+4*xi1)/3;
xi
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.