In [1]:
%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 [2]:
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 [3]:
assert True # leave this cell to grade the above integral
In [24]:
import math
In [66]:
def integrand(x, a):
return (math.sqrt(a**2 - x**2))
def integral_approx(a):
I, err = integrate.quad(integrand, 0, a, args=(a,))
return I
def integral_exact(a):
return math.pi*a**2/4
In [69]:
print("Numerical: ", integral_approx(1.0))
print("Exact: ", integral_exact(1.0))
In [ ]:
assert True # leave this cell to grade the above integral
In [61]:
def integrand(x):
return math.log(x) / (1+x)
def integral_approx():
I, err = integrate.quad(integrand, 0, 1)
return I
def integral_exact():
return -(math.pi**2)/12
In [62]:
print("Numerical: ", integral_approx())
print("Exact: ", integral_exact())
In [ ]:
assert True # leave this cell to grade the above integral
In [82]:
def integrand(x):
return x/(np.exp(x) - 1)
def integral_approx():
I, err = integrate.quad(integrand, 0, np.inf)
return I
def integral_exact():
return math.pi**2/6
In [90]:
print("Numerical: ", integral_approx())
print("Exact: ", integral_exact())
In [91]:
assert True # leave this cell to grade the above integral
In [96]:
def integrand(x,a):
return np.exp(-a*x**2)
def integral_approx(a):
I, err = integrate.quad(integrand, 0, np.inf, args=(a,))
return I
def integral_exact(a):
return 1/2 * math.sqrt(math.pi/a)
In [97]:
print("Numerical: ", integral_approx(1))
print("Exact: ", integral_exact(1))
In [ ]:
assert True # leave this cell to grade the above integral
In [88]:
def integrand(x):
return (np.sin(x)**2)
def integral_approx():
I, err = integrate.quad(integrand, 0, np.pi/2)
return I
def integral_exact():
return math.pi/4
In [89]:
print("Numerical: ", integral_approx())
print("Exact: ", integral_exact())
In [ ]:
assert True # leave this cell to grade the above integral