- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathline_length.py
65 lines (51 loc) · 1.62 KB
/
line_length.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from __future__ importannotations
importmath
fromcollections.abcimportCallable
defline_length(
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int=100,
) ->float:
"""
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 end of line segment
:param steps: an accuracy gauge; more steps increases accuracy
:return: a float representing the length of the curve
>>> def f(x):
... return x
>>> f"{line_length(f, 0, 1, 10):.6f}"
'1.414214'
>>> def f(x):
... return 1
>>> f"{line_length(f, -5.5, 4.5):.6f}"
'10.000000'
>>> def f(x):
... return math.sin(5 * x) + math.cos(10 * x) + x * x/10
>>> f"{line_length(f, 0.0, 10.0, 10000):.6f}"
'69.534930'
"""
x1=x_start
fx1=fnc(x_start)
length=0.0
for_inrange(steps):
# Approximates curve as a sequence of linear lines and sums their length
x2= (x_end-x_start) /steps+x1
fx2=fnc(x2)
length+=math.hypot(x2-x1, fx2-fx1)
# Increment step
x1=x2
fx1=fx2
returnlength
if__name__=="__main__":
deff(x):
returnmath.sin(10*x)
print("f(x) = sin(10 * x)")
print("The length of the curve from x = -10 to x = 10 is:")
i=10
whilei<=100000:
print(f"With {i} steps: {line_length(f, -10, 10, i)}")
i*=10