Integration with Python¶
GOALS:
- Approximate area under curve
- Find exact areas under curve
- Visualize area under curve
RECALL!
\[\text{Area} = \int_a^b f(x) dx = \lim_{n \to \infty} \frac{b-a}{n} \sum_{i = 1}^n f(a + i*\text{width})\]
In [1]:
%matplotlib inline
import numpy as np
import sympy as sy
import matplotlib.pyplot as plt
Problem¶
Find area under \(f(x) = x^3 - 2x\) on \([0,2]\) with
- 4 rectangles
- \(n\) rectangles as \(n \to \infty\)
In [2]:
width = (2-0)/4
In [3]:
heights = [(i**3 - 2*i) for i in [.5, 1, 1.5, 2]]
heights
Out[3]:
[-0.875, -1, 0.375, 4]
In [4]:
areas = [i*width for i in heights]
areas
Out[4]:
[-0.4375, -0.5, 0.1875, 2.0]
In [5]:
sum(areas)
Out[5]:
1.25
In [6]:
x = np.linspace(0,2, 100)
In [7]:
x
Out[7]:
array([ 0. , 0.02020202, 0.04040404, 0.06060606, 0.08080808,
0.1010101 , 0.12121212, 0.14141414, 0.16161616, 0.18181818,
0.2020202 , 0.22222222, 0.24242424, 0.26262626, 0.28282828,
0.3030303 , 0.32323232, 0.34343434, 0.36363636, 0.38383838,
0.4040404 , 0.42424242, 0.44444444, 0.46464646, 0.48484848,
0.50505051, 0.52525253, 0.54545455, 0.56565657, 0.58585859,
0.60606061, 0.62626263, 0.64646465, 0.66666667, 0.68686869,
0.70707071, 0.72727273, 0.74747475, 0.76767677, 0.78787879,
0.80808081, 0.82828283, 0.84848485, 0.86868687, 0.88888889,
0.90909091, 0.92929293, 0.94949495, 0.96969697, 0.98989899,
1.01010101, 1.03030303, 1.05050505, 1.07070707, 1.09090909,
1.11111111, 1.13131313, 1.15151515, 1.17171717, 1.19191919,
1.21212121, 1.23232323, 1.25252525, 1.27272727, 1.29292929,
1.31313131, 1.33333333, 1.35353535, 1.37373737, 1.39393939,
1.41414141, 1.43434343, 1.45454545, 1.47474747, 1.49494949,
1.51515152, 1.53535354, 1.55555556, 1.57575758, 1.5959596 ,
1.61616162, 1.63636364, 1.65656566, 1.67676768, 1.6969697 ,
1.71717172, 1.73737374, 1.75757576, 1.77777778, 1.7979798 ,
1.81818182, 1.83838384, 1.85858586, 1.87878788, 1.8989899 ,
1.91919192, 1.93939394, 1.95959596, 1.97979798, 2. ])
In [8]:
def f(x):
return x**3 - 2*x
In [10]:
f(2)
Out[10]:
4
In [11]:
plt.plot(x, f(x))
plt.fill_between(x, f(x), alpha = 0.3)
plt.title("Area under $f(x) = x^3 - 2x$")
Out[11]:
Text(0.5,1,'Area under $f(x) = x^3 - 2x$')
In [12]:
x = sy.Symbol('x')
In [13]:
sy.integrate(f(x), (x, 0, 2))
Out[13]:
0
In [14]:
sy.integrate(f(x))
Out[14]:
x**4/4 - x**2
In [15]:
(2**4)/4 - 2**2
Out[15]:
0.0