In [1]:
from scipy.integrate import quad
import numpy as np
quad(np.sin, 0, np.pi)[0]
Out[1]:
In [2]:
quad(np.log, 0, 1)[0]
Out[2]:
In [3]:
quad(lambda x: x**2, -1, 1)[0]
Out[3]:
In [4]:
quad(lambda y: y**3 - 2 * y, 0, 10)[0]
Out[4]:
In [5]:
import matplotlib.pyplot as plt
def my_cdf(x):
'''Returns the cumulative distribution function for a standard normal from -inf to x
Args:
x: the upper bound of definite integral
Returns: The probability of the interval
'''
#use np.inf for lower bound
return quad(lambda x: 1 / np.sqrt(2 * np.pi) * np.exp(-x**2 / 2), -np.inf, x)[0]
#need to vectorize it
v_cdf = np.vectorize(my_cdf)
#plot from -3 to 3 with 1000 points
x = np.linspace(-3,3,1000)
plt.plot(x, v_cdf(x))
plt.xlabel('$a$')
plt.ylabel('$P(-\infty < x < a$')
plt.show()
In [6]:
def fxn(x):
if np.abs(x) < 1:
return x**2
return x
#need to vectorize is to use with numpy
v_fxn = np.vectorize(fxn)
#integrate it
A = quad(v_fxn, -3, 3)[0]
print('The integral is {}'.format(A))
x = np.linspace(-3, 3, 1000)
plt.plot(x, v_fxn(x))
plt.xlabel('x')
plt.ylabel('f(x)')
plt.show()
In [7]:
def inner_integral(x):
return quad(lambda y: x**2 - y**2, 0, x)[0]
quad(inner_integral, 0, 3.5)[0]
Out[7]: