Integration Exercise 1

Imports


In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy import integrate

Trapezoidal rule

The trapezoidal rule generates a numerical approximation to the 1d integral:

$$ I(a,b) = \int_a^b f(x) dx $$

by dividing the interval $[a,b]$ into $N$ subdivisions of length $h$:

$$ h = (b-a)/N $$

Note that this means the function will be evaluated at $N+1$ points on $[a,b]$. The main idea of the trapezoidal rule is that the function is approximated by a straight line between each of these points.

Write a function trapz(f, a, b, N) that performs trapezoidal rule on the function f over the interval $[a,b]$ with N subdivisions (N+1 points).


In [2]:
def trapz(f, a, b, N):
    """Integrate the function f(x) over the range [a,b] with N points."""
    new = np.linspace(a,b, N+1)
    ans = np.array([(new[i+1]-new[i])*((f(new[i+1])+f(new[i]))/2) for i in range(len(new)-1)])
    return sum(ans)

In [3]:
print(trapz(lambda x: x, 0, 1, 20))


0.5

In [4]:
f = lambda x: x**2
g = lambda x: np.sin(x)

In [5]:
I = trapz(f, 0, 1, 1000)
assert np.allclose(I, 0.33333349999999995)
J = trapz(g, 0, np.pi, 1000)
assert np.allclose(J, 1.9999983550656628)

Now use scipy.integrate.quad to integrate the f and g functions and see how the result compares with your trapz function. Print the results and errors.


In [6]:
intg8, err = integrate.quad(f, 0, 1)
intg82, errr = integrate.quad(g, 0, np.pi)

In [8]:
print("Result of Integrate f: ", intg8)
print("Error of Integrate f: ", err)
print("Result of Integrate g: ", intg82)
print("Error of Integrate g: ", errr)


Result of Integrate f:  0.33333333333333337
Error of Integrate f:  3.700743415417189e-15
Result of Integrate g:  2.0
Error of Integrate g:  2.220446049250313e-14

In [ ]:
assert True # leave this cell to grade the previous one