Calculate the integral from 1/3 Simpson's Rule. Args: f (function): the equation f(x). a (float): the initial point. b (float): the final point. n (int): number of intervals. Returns: xi (float): numerical approximation of the definite integral.
(f, a, b, n)
| 4 | |
| 5 | |
| 6 | def simpson(f, a, b, n): |
| 7 | """Calculate the integral from 1/3 Simpson's Rule. |
| 8 | |
| 9 | Args: |
| 10 | f (function): the equation f(x). |
| 11 | a (float): the initial point. |
| 12 | b (float): the final point. |
| 13 | n (int): number of intervals. |
| 14 | |
| 15 | Returns: |
| 16 | xi (float): numerical approximation of the definite integral. |
| 17 | """ |
| 18 | h = (b - a) / n |
| 19 | |
| 20 | sum_odd = 0 |
| 21 | sum_even = 0 |
| 22 | |
| 23 | for i in range(0, n - 1): |
| 24 | x = a + (i + 1) * h |
| 25 | if (i + 1) % 2 == 0: |
| 26 | sum_even += f(x) |
| 27 | else: |
| 28 | sum_odd += f(x) |
| 29 | |
| 30 | xi = h / 3 * (f(a) + 2 * sum_even + 4 * sum_odd + f(b)) |
| 31 | return xi |
| 32 | |
| 33 | |
| 34 | def trapezoidal(f, a, b, n): |