TheAlgorithms-Python

Форк
0
/
area_under_curve.py 
61 строка · 1.6 Кб
1
"""
2
Approximates the area under the curve using the trapezoidal rule
3
"""
4

5
from __future__ import annotations
6

7
from collections.abc import Callable
8

9

10
def 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

51
if __name__ == "__main__":
52

53
    def f(x):
54
        return x**3 + x**2
55

56
    print("f(x) = x^3 + x^2")
57
    print("The area between the curve, x = -5, x = 5 and the x axis is:")
58
    i = 10
59
    while i <= 100000:
60
        print(f"with {i} steps: {trapezoidal_area(f, -5, 5, i)}")
61
        i *= 10
62

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.