Here is the homework assignment I'm trying to solve:
A further improvement of the approximate integration method from the last question is to divide the area under the f(x) curve into n equally-spaced trapezoids.
Based on this idea, the following formula can be derived for approximating the integral:
!(https://www.dropbox.com/s/q84mx8r5ml1q7n1/Screenshot%202017-10-01%2016.09.32.png?dl=0)!
where h is the width of the trapezoids,
h=(b−a)/n
, andxi=a+ih,i∈0,...,n
, are the coordinates of the sides of the trapezoids. The figure above visualizes the idea of the trapezoidal rule.Implement this formula in a Python function
trapezint( f,a,b,n )
. You may need to check and see if b > a, otherwise you may need to swap the variables.For instance, the result of
trapezint( math.sin,0,0.5*math.pi,10 )
should be 0.9979 (with some numerical error). The result oftrapezint( abs,-1,1,10 )
should be 2.0
This is my code but It doesn't seem to return the right values.
For print ((trapezint( math.sin,0,0.5*math.pi,10)))
I get 0.012286334153465965, when I am suppose to get 0.9979
For print (trapezint(abs, -1, 1, 10))
I get 0.18000000000000002, when I am suppose to get 1.0
.
import math
def trapezint(f,a,b,n):g = 0if b>a:h = (b-a)/float(n)for i in range (0,n):k = 0.5*h*(f(a+i*h) + f(a + (i+1)*h))g = g + kreturn gelse:a,b=b,ah = (b-a)/float(n)for i in range(0,n):k = 0.5*h*(f(a + i*h) + f(a + (i + 1)*h))g = g + kreturn gprint ((trapezint( math.sin,0,0.5*math.pi,10)))
print (trapezint(abs, -1, 1, 10))