# Approximate Integration:

Implementations of the following numerical integration techniques are given below: Left-hand Riemann sum, Right-hand Riemann sum, Midpoint Rule, Trapezoid Rule, and Simpson's Rule. Modify and evaluate the SageMath code as you wish.

Each function takes as input a function $$f$$, an interval $$[a,b]$$, and an integer $$n$$. Recall $$\Delta x = \frac{b-a}{n}$$ and $$x_i = a+i\Delta x$$ for each $$0\le i \le n$$.

### Left-Hand Riemann Sum:

The function lefthand_rs outputs the left-hand Riemann sum approximation of $$\int_a^b f(x) dx$$ using n partitions of the interval: $$\int_a^bf(x)dx \approx \sum_{i=1}^n f(x_{i-1})\Delta x = \Delta x(f(x_0)+f(x_1)+\cdots +f(x_{n-1})).$$

### Right-Hand Riemann Sum:

The function righthand_rs outputs the right-hand Riemann sum approximation of $$\int_a^b f(x) dx$$ using n partitions of the interval: $$\int_a^bf(x)dx \approx \sum_{i=1}^n f(x_{i})\Delta x = \Delta x(f(x_1)+f(x_1)+\cdots +f(x_{n})).$$

### Midpoint Rule:

The function midpoint_rule outputs the midpoint rule approximation of $$\int_a^b f(x) dx$$ using n partitions of the interval: $$\int_a^bf(x)dx \approx \sum_{i=1}^n f(\overline{x}_{i-1})\Delta x,$$ where $$\overline{x}_i$$ is the midpoint of inteval $$[x_{i-1},x_i]$$, which is $$\overline{x}_i=\frac{x_{i-1}+x_i}{2}$$.

### Trapezoid Rule:

The function trapezoid_rule outputs the trapezoid rule approximation of $$\int_a^b f(x) dx$$ using n partitions of the interval: $$\int_a^bf(x)dx \approx \frac{\Delta x}{2}(f(x_0)+2f(x_1)+2f(x_2)+ \cdots + 2f(x_{n-1})+f(x_n)).$$

### Simpsons Rule:

The function simpsons_rule outputs the Simpson's Rule approximation of $$\int_a^b f(x) dx$$ using n partitions of the interval: $$\int_a^bf(x)dx \approx \frac{\Delta x}{3}(f(x_0)+4f(x_1)+2f(x_2)+4f(x_3)+ \cdots + 2f(x_{n-2})+4f(x_{n-1})+f(x_n)).$$ Note: n must be even.

#### Piecewise Defined Functions:

Sometimes you may find the need to define $$f$$ as a piecewise defined function. For example, suppose you are trying to approximate the integral $$\int_{0}^{10} f(x)~dx$$ where $$f(x)=\begin{cases} \displaystyle x,&x\le 5\\ x^2,&x > 5\\ \end{cases}$$ (not that you would not need to approximate in this case since you can easily find antiderivates, but we'll just use it as a simple example).

We can replace the line "f(x) = ..." in the code above with a python function defining $$f$$:
def f(x):
if x<=5:
return x;
elif x>5:   # elif means "else if"
return x^2;
Try to cut-and-paste this code to replace the function $$f$$ in Simpson's Rule above.