Skip to content

Commit 7addbcc

Browse files
Torus volume (TheAlgorithms#7905)
* Added Torus volume algorithm * Updated Torus volume for simplicity (removed ref to vol_sphere()) * Refactoring * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 6c15f52 commit 7addbcc

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

maths/volume.py

+29
Original file line numberDiff line numberDiff line change
@@ -441,6 +441,34 @@ def vol_conical_frustum(height: float, radius_1: float, radius_2: float) -> floa
441441
)
442442

443443

444+
def vol_torus(torus_radius: float, tube_radius: float) -> float:
445+
"""Calculate the Volume of a Torus.
446+
Wikipedia reference: https://en.wikipedia.org/wiki/Torus
447+
:return 2pi^2 * torus_radius * tube_radius^2
448+
>>> vol_torus(1, 1)
449+
19.739208802178716
450+
>>> vol_torus(4, 3)
451+
710.6115168784338
452+
>>> vol_torus(3, 4)
453+
947.4820225045784
454+
>>> vol_torus(1.6, 1.6)
455+
80.85179925372404
456+
>>> vol_torus(0, 0)
457+
0.0
458+
>>> vol_torus(-1, 1)
459+
Traceback (most recent call last):
460+
...
461+
ValueError: vol_torus() only accepts non-negative values
462+
>>> vol_torus(1, -1)
463+
Traceback (most recent call last):
464+
...
465+
ValueError: vol_torus() only accepts non-negative values
466+
"""
467+
if torus_radius < 0 or tube_radius < 0:
468+
raise ValueError("vol_torus() only accepts non-negative values")
469+
return 2 * pow(pi, 2) * torus_radius * pow(tube_radius, 2)
470+
471+
444472
def main():
445473
"""Print the Results of Various Volume Calculations."""
446474
print("Volumes:")
@@ -453,6 +481,7 @@ def main():
453481
print(f"Sphere: {vol_sphere(2) = }") # ~= 33.5
454482
print(f"Hemisphere: {vol_hemisphere(2) = }") # ~= 16.75
455483
print(f"Circular Cylinder: {vol_circular_cylinder(2, 2) = }") # ~= 25.1
484+
print(f"Torus: {vol_torus(2, 2) = }") # ~= 157.9
456485
print(f"Conical Frustum: {vol_conical_frustum(2, 2, 4) = }") # ~= 58.6
457486
print(f"Spherical cap: {vol_spherical_cap(1, 2) = }") # ~= 5.24
458487
print(f"Spheres intersetion: {vol_spheres_intersect(2, 2, 1) = }") # ~= 21.21

0 commit comments

Comments
 (0)