Skip to content

Commit 2a2f207

Browse files
authored
Added volume_of_torus algorithm in maths
Implemented the formula for the volume of a torus with type hints and doctests.
1 parent 2e2d33a commit 2a2f207

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

maths/volume_of_torus.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""
2+
Volume of a Torus
3+
Reference: https://en.wikipedia.org/wiki/Torus
4+
"""
5+
6+
from math import pi
7+
8+
9+
def volume_of_torus(major_radius: float, minor_radius: float) -> float:
10+
"""
11+
Calculate the volume of a torus.
12+
13+
Formula:
14+
V = 2 * π² * R * r²
15+
16+
:param major_radius: Distance from the center of the tube to the center of the torus (R)
17+
:param minor_radius: Radius of the tube (r)
18+
:return: Volume of the torus
19+
20+
>>> volume_of_torus(3.0, 1.0)
21+
59.21762640653615
22+
>>> volume_of_torus(5.0, 2.0)
23+
394.7841760435743
24+
>>> volume_of_torus(0.0, 0.0)
25+
0.0
26+
"""
27+
if major_radius < 0:
28+
raise ValueError("major_radius must be non-negative")
29+
if minor_radius < 0:
30+
raise ValueError("minor_radius must be non-negative")
31+
32+
return 2 * (pi ** 2) * major_radius * (minor_radius ** 2)
33+
34+
35+
if __name__ == "__main__":
36+
import doctest
37+
38+
doctest.testmod()

0 commit comments

Comments
 (0)