0

I want to build a function that takes in the tolerance level, upper and lower bounds, and the function, to calculate the Adaptive Trapezoidal Quadrature, as well as drawing a figure, such as this one:enter image description here

Because I need the node values to draw my figure, I tried coding as follows:

function [node, approx] = aq(f,a,b,tol)
t = (b-a)*(f(b)+f(a))/2;
    if abs((t2 - t)/3) > tol %Since T(2)-T(1)=E(1)-E(2)=3*E(2)
        m = (a+b)/2;
        [node1, approx1] = aq(f,a,m,tol/2);
        [node2, approx2] = aq(f,m,b,tol/2);
        node = [node1(1:end-1) node2];
        approx = approx1+approx2;
    else
        node = [a,b];
        approx = tf;
    end
end

I have two problems with my code: One is that, obviously, t2 is not defined. I do not know how to define it because, depending on whether the quadrature rule, the next estimation could include both sides of the trapezoid or just one. I'm confused. Maybe I need to define a separate function that calculates trapezoidal area.

The second problem is that even if I put in a function with its known integral value (for example,

tol = 10^-2;

f = @(x) exp(x)*sin(x);

a=0; b=pi;

.5*(exp(pi)+1) %is our exact integral value, we can put this into the if statement

But the code goes into infinite loop. I don't know how to stop this, because theoretically, it's supposed to converge.

Please go easy on me as I am a math major in a numerical analysis class, and this is my first year coding. Thanks!

Edit: Thanks! Got it to work :) enter image description here

Community
  • 1
  • 1
SKYejin
  • 107
  • 5

1 Answers1

1

By context, t2 is the composite trapezoidal formula for two segments,

t2 = (b-a)/2*(f(a)+2*f(m)+f(b))/2

The error is then the second iterated difference, with some factor in front,

(t2-t)/3 = (b-a)/4*(-f(a)+2*f(m)-f(b))

and the Richardson extrapolation of the trapezoidal values is the Simpson value

tf = (4*t2-t)/3 = (b-a)/6*(f(a)+4*f(m)+f(b))

You should introduce some data structure or other mechanism to remove the multiple evaluation of f at the same points. It is not overly critical, but might remove a non-trivial factor from the computation time.

Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51