Approximates the arc length of a line segment by treating the curve as a sequence of linear lines and summing their lengths :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
(
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
)
| 5 | |
| 6 | |
| 7 | def line_length( |
| 8 | fnc: Callable[[float], float], |
| 9 | x_start: float, |
| 10 | x_end: float, |
| 11 | steps: int = 100, |
| 12 | ) -> float: |
| 13 | """ |
| 14 | Approximates the arc length of a line segment by treating the curve as a |
| 15 | sequence of linear lines and summing their lengths |
| 16 | :param fnc: a function which defines a curve |
| 17 | :param x_start: left end point to indicate the start of line segment |
| 18 | :param x_end: right end point to indicate end of line segment |
| 19 | :param steps: an accuracy gauge; more steps increases accuracy |
| 20 | :return: a float representing the length of the curve |
| 21 | |
| 22 | >>> def f(x): |
| 23 | ... return x |
| 24 | >>> f"{line_length(f, 0, 1, 10):.6f}" |
| 25 | '1.414214' |
| 26 | |
| 27 | >>> def f(x): |
| 28 | ... return 1 |
| 29 | >>> f"{line_length(f, -5.5, 4.5):.6f}" |
| 30 | '10.000000' |
| 31 | |
| 32 | >>> def f(x): |
| 33 | ... return math.sin(5 * x) + math.cos(10 * x) + x * x/10 |
| 34 | >>> f"{line_length(f, 0.0, 10.0, 10000):.6f}" |
| 35 | '69.534930' |
| 36 | """ |
| 37 | |
| 38 | x1 = x_start |
| 39 | fx1 = fnc(x_start) |
| 40 | length = 0.0 |
| 41 | |
| 42 | for _ in range(steps): |
| 43 | # Approximates curve as a sequence of linear lines and sums their length |
| 44 | x2 = (x_end - x_start) / steps + x1 |
| 45 | fx2 = fnc(x2) |
| 46 | length += math.hypot(x2 - x1, fx2 - fx1) |
| 47 | |
| 48 | # Increment step |
| 49 | x1 = x2 |
| 50 | fx1 = fx2 |
| 51 | |
| 52 | return length |
| 53 | |
| 54 | |
| 55 | if __name__ == "__main__": |