MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / trapezoidal_rule

Function trapezoidal_rule

maths/trapezoidal_rule.py:6–33  ·  view source on GitHub ↗

Implements the extended trapezoidal rule for numerical integration. The function f(x) is provided below. :param boundary: List containing the lower and upper bounds of integration [a, b] :param steps: The number of steps (intervals) used in the approximation :return: The numeri

(boundary, steps)

Source from the content-addressed store, hash-verified

4
5
6def trapezoidal_rule(boundary, steps):
7 """
8 Implements the extended trapezoidal rule for numerical integration.
9 The function f(x) is provided below.
10
11 :param boundary: List containing the lower and upper bounds of integration [a, b]
12 :param steps: The number of steps (intervals) used in the approximation
13 :return: The numerical approximation of the integral
14
15 >>> abs(trapezoidal_rule([0, 1], 10) - 0.33333) < 0.01
16 True
17 >>> abs(trapezoidal_rule([0, 1], 100) - 0.33333) < 0.01
18 True
19 >>> abs(trapezoidal_rule([0, 2], 1000) - 2.66667) < 0.01
20 True
21 >>> abs(trapezoidal_rule([1, 2], 1000) - 2.33333) < 0.01
22 True
23 """
24 h = (boundary[1] - boundary[0]) / steps
25 a = boundary[0]
26 b = boundary[1]
27 x_i = make_points(a, b, h)
28 y = 0.0
29 y += (h / 2.0) * f(a)
30 for i in x_i:
31 y += h * f(i)
32 y += (h / 2.0) * f(b)
33 return y
34
35
36def make_points(a, b, h):

Callers 1

mainFunction · 0.85

Calls 2

make_pointsFunction · 0.70
fFunction · 0.70

Tested by

no test coverage detected