In [35]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy import integrate
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 [36]:
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 [37]:
assert True # leave this cell to grade the above integral
In [38]:
def integrand1(x,p):
return (np.sin(p*x)**2)/(x**2)
def integral_approx1(p):
I1, e1 = integrate.quad(integrand1, 0, np.inf, args=(p,))
return I1
def integral_exact1(p):
return np.pi*p/2
print("Numerical: ", integral_approx1(1.0))
print("Exact : ", integral_exact1(1.0))
In [39]:
assert True # leave this cell to grade the above integral
In [40]:
def integrand2(x):
return (np.sin(x))**2
def integral_approx2():
I2, e2 = integrate.quad(integrand2, 0, np.pi/2)
return I2
def integral_exact2():
return np.pi/4
print("Numerical: ", integral_approx2())
print("Exact : ", integral_exact2())
In [41]:
assert True # leave this cell to grade the above integral
In [42]:
def integrand3(x,a,b):
return np.exp(-a*x)*np.cos(b*x)
def integral_approx3(a,b):
I3, e3 = integrate.quad(integrand3, 0, np.inf, args=(a,b,))
return I3
def integral_exact3(a,b):
return a/(a**2+b**2)
print("Numerical: ", integral_approx3(1.0,1.0))
print("Exact : ", integral_exact3(1.0,1.0))
In [43]:
assert True # leave this cell to grade the above integral
In [44]:
def integrand4(x):
return x/(np.exp(x)-1)
def integral_approx4():
I4, e4 = integrate.quad(integrand4, 0, np.inf)
return I4
def integral_exact4():
return np.pi**2/6
print("Numerical: ", integral_approx4())
print("Exact : ", integral_exact4())
In [45]:
assert True # leave this cell to grade the above integral
In [46]:
def integrand5(x):
return (np.log(1+x))/(x)
def integral_approx5():
I5, e5 = integrate.quad(integrand5, 0, 1)
return I5
def integral_exact5():
return (np.pi**2)/12
print("Numerical: ", integral_approx5())
print("Exact : ", integral_exact5())
In [47]:
assert True # leave this cell to grade the above integral