2020-01-18 17:25:27 +00:00
|
|
|
"""
|
|
|
|
Approximates the area under the curve using the trapezoidal rule
|
|
|
|
"""
|
2021-09-07 11:37:03 +00:00
|
|
|
from __future__ import annotations
|
2020-01-18 17:25:27 +00:00
|
|
|
|
2022-07-11 08:19:52 +00:00
|
|
|
from collections.abc import Callable
|
2020-01-18 17:25:27 +00:00
|
|
|
|
2020-01-23 16:21:51 +00:00
|
|
|
|
|
|
|
def trapezoidal_area(
|
2023-08-09 07:55:30 +00:00
|
|
|
fnc: Callable[[float], float],
|
|
|
|
x_start: float,
|
|
|
|
x_end: float,
|
2020-01-23 16:21:51 +00:00
|
|
|
steps: int = 100,
|
|
|
|
) -> float:
|
2020-01-18 17:25:27 +00:00
|
|
|
"""
|
|
|
|
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
|
|
|
|
:param steps: an accuracy gauge; more steps increases the accuracy
|
|
|
|
:return: a float representing the length of the curve
|
|
|
|
|
|
|
|
>>> def f(x):
|
|
|
|
... return 5
|
|
|
|
>>> '%.3f' % trapezoidal_area(f, 12.0, 14.0, 1000)
|
|
|
|
'10.000'
|
|
|
|
|
|
|
|
>>> def f(x):
|
|
|
|
... return 9*x**2
|
|
|
|
>>> '%.4f' % trapezoidal_area(f, -4.0, 0, 10000)
|
|
|
|
'192.0000'
|
|
|
|
|
|
|
|
>>> '%.4f' % trapezoidal_area(f, -4.0, 4.0, 10000)
|
|
|
|
'384.0000'
|
|
|
|
"""
|
|
|
|
x1 = x_start
|
|
|
|
fx1 = fnc(x_start)
|
|
|
|
area = 0.0
|
|
|
|
|
2022-10-13 16:03:06 +00:00
|
|
|
for _ in range(steps):
|
2020-01-18 17:25:27 +00:00
|
|
|
# Approximates small segments of curve as linear and solve
|
|
|
|
# for trapezoidal area
|
2020-01-23 16:21:51 +00:00
|
|
|
x2 = (x_end - x_start) / steps + x1
|
2020-01-18 17:25:27 +00:00
|
|
|
fx2 = fnc(x2)
|
2020-01-23 16:21:51 +00:00
|
|
|
area += abs(fx2 + fx1) * (x2 - x1) / 2
|
2020-01-18 17:25:27 +00:00
|
|
|
|
|
|
|
# Increment step
|
|
|
|
x1 = x2
|
|
|
|
fx1 = fx2
|
|
|
|
return area
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
|
|
|
def f(x):
|
2022-01-30 19:29:54 +00:00
|
|
|
return x**3
|
2020-01-18 17:25:27 +00:00
|
|
|
|
|
|
|
print("f(x) = x^3")
|
|
|
|
print("The area between the curve, x = -10, x = 10 and the x axis is:")
|
|
|
|
i = 10
|
|
|
|
while i <= 100000:
|
|
|
|
area = trapezoidal_area(f, -5, 5, i)
|
2020-10-21 10:46:14 +00:00
|
|
|
print(f"with {i} steps: {area}")
|
2020-01-23 16:21:51 +00:00
|
|
|
i *= 10
|