TheAlgorithms-Python
61 строка · 1.6 Кб
1"""
2Approximates the area under the curve using the trapezoidal rule
3"""
4
5from __future__ import annotations
6
7from collections.abc import Callable
8
9
10def trapezoidal_area(
11fnc: Callable[[float], float],
12x_start: float,
13x_end: float,
14steps: int = 100,
15) -> float:
16"""
17Treats curve as a collection of linear lines and sums the area of the
18trapezium 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"""
36x1 = x_start
37fx1 = fnc(x_start)
38area = 0.0
39for _ in range(steps):
40# Approximates small segments of curve as linear and solve
41# for trapezoidal area
42x2 = (x_end - x_start) / steps + x1
43fx2 = fnc(x2)
44area += abs(fx2 + fx1) * (x2 - x1) / 2
45# Increment step
46x1 = x2
47fx1 = fx2
48return area
49
50
51if __name__ == "__main__":
52
53def f(x):
54return x**3 + x**2
55
56print("f(x) = x^3 + x^2")
57print("The area between the curve, x = -5, x = 5 and the x axis is:")
58i = 10
59while i <= 100000:
60print(f"with {i} steps: {trapezoidal_area(f, -5, 5, i)}")
61i *= 10
62