Skip to content

Commit 007f972

Browse files
author
Turgut
committed
Add Hooke's Law implementation to physics
1 parent 68473af commit 007f972

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

physics/hookes_law.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""
2+
Hooke's Law states that the force needed to extend or compress a spring
3+
is proportional to the distance of that extension or compression.
4+
5+
F = -k * x
6+
7+
Where:
8+
F = Force applied (in Newtons)
9+
k = Spring constant (in Newtons per meter, N/m)
10+
x = Displacement from equilibrium (in meters)
11+
12+
The negative sign indicates the force is a restoring force (opposite to displacement).
13+
14+
Reference: https://en.wikipedia.org/wiki/Hooke%27s_law
15+
"""
16+
17+
18+
def hookes_law(spring_constant: float, displacement: float) -> float:
19+
"""
20+
Calculate the restoring force of a spring using Hooke's Law.
21+
22+
Parameters:
23+
spring_constant: stiffness of the spring in N/m (must be positive)
24+
displacement: extension or compression in meters
25+
26+
Returns:
27+
Restoring force in Newtons (negative means opposing displacement)
28+
29+
>>> hookes_law(spring_constant=50, displacement=0.1)
30+
-5.0
31+
>>> hookes_law(spring_constant=100, displacement=0.5)
32+
-50.0
33+
>>> hookes_law(spring_constant=200, displacement=-0.2)
34+
40.0
35+
>>> hookes_law(spring_constant=0, displacement=0.1)
36+
Traceback (most recent call last):
37+
...
38+
ValueError: Spring constant must be positive.
39+
>>> hookes_law(spring_constant=-10, displacement=0.1)
40+
Traceback (most recent call last):
41+
...
42+
ValueError: Spring constant must be positive.
43+
"""
44+
if spring_constant <= 0:
45+
raise ValueError("Spring constant must be positive.")
46+
return -spring_constant * displacement
47+
48+
49+
if __name__ == "__main__":
50+
import doctest
51+
52+
doctest.testmod()

0 commit comments

Comments
 (0)