Inducción al uso de Python

Práctica: Integración numérica

Objectives

During this activity, students should be able to:


Activity Description

Simpson’s rule is a method for numeric integration:

$$ \int_{a}^{b}f=\frac{h}{3}(y_0 + 4y_1 + 2y_2 + 4y_3 + 2y_4 + \cdots + 2y_{n-2} + 4y_{n-1} + y_n) $$

Where \( n \) is an even positive integer (if you increment the value of \( n \) you get a better approximation), and \( h \) and \( y_k \) are defined as follows:

$$ h = \frac{b - a}{n} $$ $$ y_k = f(a + kh) $$

Write the function integral, that takes as arguments a, b, n, and f. It returns the value of the integral, using Simpson’s rule.

Test your code with the following integrals:

$$ \int_{0}^{1} x^3\textit{dx} = \frac{1}{4} $$ $$ \int_{0}^{1}\frac{4}{1+x^2}\mathit{dx} = \pi $$