In [7]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy import integrate
from math import sqrt
Here is a table of definite integrals. Many of these integrals has a number of parameters $a$, $b$, etc.
Find five of these integrals and perform the following steps:
integrand
function that computes the value of the integrand.integral_approx
funciton that uses scipy.integrate.quad
to peform the integral.integral_exact
function that computes the exact value of the integral.integral_approx
and integral_exact
for one set of parameters.Here is an example to show what your solutions should look like:
Here is the integral I am performing:
$$ I_1 = \int_0^\infty \frac{dx}{x^2 + a^2} = \frac{\pi}{2a} $$
In [8]:
def integrand(x, a):
return 1.0/(x**2 + a**2)
def integral_approx(a):
# Use the args keyword argument to feed extra arguments to your integrand
I, e = integrate.quad(integrand, 0, np.inf, args=(a,))
return I
def integral_exact(a):
return 0.5*np.pi/a
print("Numerical: ", integral_approx(1.0))
print("Exact : ", integral_exact(1.0))
In [9]:
assert True # leave this cell to grade the above integral
In [21]:
def integrand_1(x, a):
return (1) / (1 - 2 * a * np.cos(x) + a**2)
def integral_approx_1(a):
I, e = integrate.quad(integrand_1, 0, 2 * np.pi, args = (a,))
return I
def integral_exact_1(a):
return (2 * np.pi) / (1 - a**2)
print("Numerical:", integral_approx_1(0.5))
print("Exact:", integral_exact_1(0.5))
In [ ]:
assert True # leave this cell to grade the above integral
In [22]:
def integrand_2(x, a):
return sqrt(a**2 - x**2)
def integral_approx_2(a):
I, e = integrate.quad(integrand_2, 0, a, args = (a,))
return I
def integral_exact_2(a):
return (a**2 * np.pi) / (4)
print("Numerical:", integral_approx_2(0.5))
print("Exact:", integral_exact_2(0.5))
In [ ]:
assert True # leave this cell to grade the above integral
In [25]:
def integrand_3(x, p):
return ((np.sin(p * x))**2) / (x**2)
def integral_approx_3(p):
I, e = integrate.quad(integrand_3, 0, np.inf, args = (p,))
return I
def integral_exact_3(p):
return (p * np.pi) / (2)
print("Numerical:", integral_approx_3(5))
print("Exact:", integral_exact_3(5))
In [ ]:
assert True # leave this cell to grade the above integral
In [26]:
def integrand_4(x, p):
return (1 - np.cos(p * x)) / (x**2)
def integral_approx_4(p):
I, e = integrate.quad(integrand_4, 0, np.inf, args = (p,))
return I
def integral_exact_4(p):
return (p * np.pi) / (2)
print("Numerical:", integral_approx_4(10))
print("Exact:", integral_exact_4(10))
In [ ]:
assert True # leave this cell to grade the above integral
In [33]:
def integrand_5(x, a):
return (np.log(x)) / (x**2 + a**2)
def integral_approx_5(a):
I, e = integrate.quad(integrand_5, 0, np.inf, args = (a,))
return I
def integral_exact_5(a):
return ((np.pi) * np.log(a)) / (2 * a)
print("Numerical:", integral_approx_5(25))
print("Exact:", integral_exact_5(25))
In [ ]:
assert True # leave this cell to grade the above integral