# Integration¶

In [8]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline


## Simple numerical integration¶

$$I = \int_a^bf(x)dx.$$$$I \approx \sum_{i=0}^{N_{rec}-1}f(x_i)\Delta x,$$$$\Delta x = \frac{b-a}{N_{rec}},$$$$x_i = i\Delta x.$$

• In the figure,
• $b-a=5-0 = 5$
• $N_{rec}=5$
• $\Delta x=(b-a)/N_{rec} = 1$

### Exercise 1¶

Find the following integral as simply as you can.

$$I = \int_0^{\pi/2}\cos(x)dx$$

again:

$$I \approx \sum_{i=0}^{N_{rec}-1}f(x_i)\Delta x$$
In [ ]:



### Exercise 2¶

• Solve same problem as in Exercise 1: $$I = \int_0^{\pi/2}\cos(x)dx$$
• This time, write a a function called integrate that takes the following arguments:
• A function f to integrate,
• The upper and lower bounds a, b
• The number of rectangles to use.
• The function returns the integral.

#### Notes¶

• Start easy, then add complexity.
• Think through the steps.
• What variables or arrays do you need? Do they need to be initialized?
• How to treat the sum?
In [ ]:



## Trapazoid integration¶

• In the simple version above, we used rectangles.
• Try this with trapazoids instead.
• $N_{trap}$ is the number of trapazoids ($N_{trap}=5$).
• We have $N_{trap}+1$ points (6 points).

\begin{align} I_0 &= \frac{\Delta x}{2}(f_0+f_1), \\ I_1 &= \frac{\Delta x}{2}(\phantom{f_0+}f_1+f_2), \\ I_2 &= \frac{\Delta x}{2}(\phantom{f_0+f_1+}f_2+f_3), \\ I_3 &= \frac{\Delta x}{2}(\phantom{f_0+f_1+f_2+}f_3+f_4), \\ I_4 &= \frac{\Delta x}{2}(\phantom{f_0+f_1+f_2+f_3+}f_4+f_5). \\ \end{align}$$I = \left(\Delta x\sum_{i=0}^{5}f_i\right) -\frac{\Delta x}{2}(f_0+f_{5}).$$

$$I = \left(\Delta x\sum_{i=0}^{N_{trap}}f_i\right) -\frac{\Delta x}{2}(f_0+f_{N_{trap}}).$$

• Note the overlap of the terms: two of every $f$ value except first and last.
• So, we double all of them and then subtract the first and last.

### Exercise¶

• Write a a function called integrate_trap that takes the following arguments:
• A function f to integrate,
• The upper and lower bounds a, b
• The number of trapazoids to use.
• The function returns the integral.
• Try it out on the following:
$$I = \int_0^{\pi/2}\cos(x)dx$$

#### Notes¶

• You can reuse and edit your code from the previous exercise.