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

Function trapezoidal_area

maths/area_under_curve.py:10–48  ·  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 >>> f"{trapezoidal_area(f, 12.0, 14.0, 1000):.3f}"
28 '10.000'
29 >>> def f(x):
30 ... return 9*x**2
31 >>> f"{trapezoidal_area(f, -4.0, 0, 10000):.4f}"
32 '192.0000'
33 >>> f"{trapezoidal_area(f, -4.0, 4.0, 10000):.4f}"
34 '384.0000'
35 """
36 x1 = x_start
37 fx1 = fnc(x_start)
38 area = 0.0
39 for _ in range(steps):
40 # Approximates small segments of curve as linear and solve
41 # for trapezoidal area
42 x2 = (x_end - x_start) / steps + x1
43 fx2 = fnc(x2)
44 area += abs(fx2 + fx1) * (x2 - x1) / 2
45 # Increment step
46 x1 = x2
47 fx1 = fx2
48 return area
49
50
51if __name__ == "__main__":

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected