-
-
Notifications
You must be signed in to change notification settings - Fork 50.4k
Expand file tree
/
Copy pathhookes_law.py
More file actions
52 lines (40 loc) · 1.53 KB
/
hookes_law.py
File metadata and controls
52 lines (40 loc) · 1.53 KB
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
"""
Hooke's Law states that the force needed to extend or compress a spring
is proportional to the distance of that extension or compression.
F = -k * x
Where:
F = Force applied (in Newtons)
k = Spring constant (in Newtons per meter, N/m)
x = Displacement from equilibrium (in meters)
The negative sign indicates the force is a restoring force (opposite to displacement).
Reference: https://en.wikipedia.org/wiki/Hooke%27s_law
"""
def hookes_law(spring_constant: float, displacement: float) -> float:
"""
Calculate the restoring force of a spring using Hooke's Law.
Parameters:
spring_constant: stiffness of the spring in N/m (must be positive)
displacement: extension or compression in meters
Returns:
Restoring force in Newtons (negative means opposing displacement)
>>> hookes_law(spring_constant=50, displacement=0.1)
-5.0
>>> hookes_law(spring_constant=100, displacement=0.5)
-50.0
>>> hookes_law(spring_constant=200, displacement=-0.2)
40.0
>>> hookes_law(spring_constant=0, displacement=0.1)
Traceback (most recent call last):
...
ValueError: Spring constant must be positive.
>>> hookes_law(spring_constant=-10, displacement=0.1)
Traceback (most recent call last):
...
ValueError: Spring constant must be positive.
"""
if spring_constant <= 0:
raise ValueError("Spring constant must be positive.")
return -spring_constant * displacement
if __name__ == "__main__":
import doctest
doctest.testmod()