Integral Approximation Methods

132 days ago by MACH

Here is a domain description that describes an interval beginning at a, jumping by steps of dx, and ending at b - dx:

def domain(a,b,dx): return [a,a+dx..b-dx] 
       

We will use it to compare four integral approximation methods that divide the area between a function and the x axis into a set of polygons:

def LRAM(f,a,b,dx): return sum([f(x) for x in domain(a,b,dx)])*dx def RRAM(f,a,b,dx): return sum([f(x+dx) for x in domain(a,b,dx)])*dx def MRAM(f,a,b,dx): return sum([f(x+dx/2) for x in domain(a,b,dx)])*dx def TRAP(f,a,b,dx): return sum([(f(x)+f(x+dx))/2 for x in domain(a,b,dx)])*dx 
       

Notice how efficiently the list comprehension expressions allow us to compare and contrast the methods.

And here are four corresponding functions that will create lists of the vertices of the polygons determined by each method:

def LRAM_vertices(f,a,b,dx): return [[(x,0),(x,f(x)),(x+dx,f(x)),(x+dx,0)] for x in domain(a,b,dx)] def RRAM_vertices(f,a,b,dx): return [[(x,0),(x,f(x+dx)),(x+dx,f(x+dx)),(x+dx,0)] for x in domain(a,b,dx)] def MRAM_vertices(f,a,b,dx): return [[(x,0),(x,f(x+dx/2)),(x+dx,f(x+dx/2)),(x+dx,0)] for x in domain(a,b,dx)] def TRAP_vertices(f,a,b,dx): return [[(x,0),(x,f(x)),(x+dx,f(x+dx)),(x+dx,0)] for x in domain(a,b,dx)] 
       

Finally, here is an interactive cell that pulls all of the preceding together.

The initial default for f(x) is \sin(x), but you can easily change it in the input box that opens up.

Same for a, b, dx, and the approximation method used:

f(x) = sin(x) def polygons(method): return sum([polygon(P,color=(random(),random(),random())) for P in method]) @interact def _(f=f,a=0,b=pi,dx=pi/12,method = ['None','LRAM','RRAM','MRAM','TRAP']): graph = plot(f,a,b,color='red') if method == 'LRAM': graph += polygons(LRAM_vertices(f,a,b,dx)) approx = LRAM(f,a,b,dx).n() elif method == 'RRAM': graph += polygons(RRAM_vertices(f,a,b,dx)) approx = RRAM(f,a,b,dx).n() elif method == 'MRAM': graph += polygons(MRAM_vertices(f,a,b,dx)) approx = MRAM(f,a,b,dx).n() elif method == 'TRAP': graph += polygons(TRAP_vertices(f,a,b,dx)) approx = TRAP(f,a,b,dx).n() actual = f(x).integral(x,a,b).n() show(f) if method != 'None': print 'Approximate area:', approx print 'Actual area:', actual print 'Difference:',approx - actual show(graph, aspect_ratio = 1) 
       

Click to the left again to hide and once more to show the dynamic interactive window

Sage can find the exact value of an integral:

f(x) = x^2 
       
f.integral(x) 
       
f.integral(x)(9) 
       

Experiment with different functions on your own.

Sage can also find derivatives:

f.derivative(x) 
       
f.derivative(x)(9)