Problem 1 Instructions

Evaluate the following definite integrals using the quad function and the lambda keyword. You may only report your answer in Python and you should only print the integral area and nothing else. Do not define a function, use lambda to define your integrands if necessary

1.1

$$ \int_0^\pi \sin x\, dx $$

In [1]:
from scipy.integrate import quad
import numpy as np

quad(np.sin, 0, np.pi)[0]


Out[1]:
2.0

1.2

$$ \int_0^1 \ln x\, dx $$

In [2]:
quad(np.log, 0, 1)[0]


Out[2]:
-0.9999999999999999

1.3

$$ \int_{-1}^1 x^2 \, dx $$

In [3]:
quad(lambda x: x**2, -1, 1)[0]


Out[3]:
0.6666666666666666

1.1

$$ \int_0^{10} y^3 - 2 y \, dy $$

In [4]:
quad(lambda y: y**3 - 2 * y, 0, 10)[0]


Out[4]:
2400.0

Problem 2 Instruction

Answer the following questions in Python

2.1

Create and plot a function which integrates the standard normal distribution from $-\infty$ to the given argument. Plot from $-3$ to $3$. You may not use scipy.stats and you should evaluate the integral yourself using quad.


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()


2.2

Define the following piecewise function in Python, plot it and integrate it from -3 to 3:

$$ f(x) = \; \left. \begin{array}{llr} x^2 & \textrm{if} & |x| < 1\\ x & \textrm{otherwise} & \\ \end{array}\right\} $$

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()


The integral is 0.6666666666666664

2.3

Evaluate the following integral:

$$ \int_0^{3.5}\int_0^x x^2 - y^2 \,dy\, dx $$

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]:
25.010416666666668