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

Function trapezoidal_area

maths/numerical_analysis/numerical_integration.py:10–52  ·  view source on GitHub ↗

Treats curve as a collection of linear lines and sums the area of the trapezium shape they form :param fnc: a function which defines a curve :param x_start: left end point to indicate the start of line segment :param x_end: right end point to indicate end of line segment :pa

(
    fnc: Callable[[float], float],
    x_start: float,
    x_end: float,
    steps: int = 100,
)

Source from the content-addressed store, hash-verified

8
9
10def trapezoidal_area(
11 fnc: Callable[[float], float],
12 x_start: float,
13 x_end: float,
14 steps: int = 100,
15) -> float:
16 """
17 Treats curve as a collection of linear lines and sums the area of the
18 trapezium shape they form
19 :param fnc: a function which defines a curve
20 :param x_start: left end point to indicate the start of line segment
21 :param x_end: right end point to indicate end of line segment
22 :param steps: an accuracy gauge; more steps increases the accuracy
23 :return: a float representing the length of the curve
24
25 >>> def f(x):
26 ... return 5
27 >>> '%.3f' % trapezoidal_area(f, 12.0, 14.0, 1000)
28 '10.000'
29
30 >>> def f(x):
31 ... return 9*x**2
32 >>> '%.4f' % trapezoidal_area(f, -4.0, 0, 10000)
33 '192.0000'
34
35 >>> '%.4f' % trapezoidal_area(f, -4.0, 4.0, 10000)
36 '384.0000'
37 """
38 x1 = x_start
39 fx1 = fnc(x_start)
40 area = 0.0
41
42 for _ in range(steps):
43 # Approximates small segments of curve as linear and solve
44 # for trapezoidal area
45 x2 = (x_end - x_start) / steps + x1
46 fx2 = fnc(x2)
47 area += abs(fx2 + fx1) * (x2 - x1) / 2
48
49 # Increment step
50 x1 = x2
51 fx1 = fx2
52 return area
53
54
55if __name__ == "__main__":

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected