Skip to content

Commit 6c15f52

Browse files
Added Torus surface area (TheAlgorithms#7906)
* Added Torus surface area * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fixed error in test Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 6cd7c49 commit 6c15f52

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

maths/area.py

+35
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,40 @@ def surface_area_cylinder(radius: float, height: float) -> float:
201201
return 2 * pi * radius * (height + radius)
202202

203203

204+
def surface_area_torus(torus_radius: float, tube_radius: float) -> float:
205+
"""Calculate the Area of a Torus.
206+
Wikipedia reference: https://en.wikipedia.org/wiki/Torus
207+
:return 4pi^2 * torus_radius * tube_radius
208+
>>> surface_area_torus(1, 1)
209+
39.47841760435743
210+
>>> surface_area_torus(4, 3)
211+
473.7410112522892
212+
>>> surface_area_torus(3, 4)
213+
Traceback (most recent call last):
214+
...
215+
ValueError: surface_area_torus() does not support spindle or self intersecting tori
216+
>>> surface_area_torus(1.6, 1.6)
217+
101.06474906715503
218+
>>> surface_area_torus(0, 0)
219+
0.0
220+
>>> surface_area_torus(-1, 1)
221+
Traceback (most recent call last):
222+
...
223+
ValueError: surface_area_torus() only accepts non-negative values
224+
>>> surface_area_torus(1, -1)
225+
Traceback (most recent call last):
226+
...
227+
ValueError: surface_area_torus() only accepts non-negative values
228+
"""
229+
if torus_radius < 0 or tube_radius < 0:
230+
raise ValueError("surface_area_torus() only accepts non-negative values")
231+
if torus_radius < tube_radius:
232+
raise ValueError(
233+
"surface_area_torus() does not support spindle or self intersecting tori"
234+
)
235+
return 4 * pow(pi, 2) * torus_radius * tube_radius
236+
237+
204238
def area_rectangle(length: float, width: float) -> float:
205239
"""
206240
Calculate the area of a rectangle.
@@ -543,6 +577,7 @@ def area_reg_polygon(sides: int, length: float) -> float:
543577
print(f"Cone: {surface_area_cone(10, 20) = }")
544578
print(f"Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }")
545579
print(f"Cylinder: {surface_area_cylinder(10, 20) = }")
580+
print(f"Torus: {surface_area_torus(20, 10) = }")
546581
print(f"Equilateral Triangle: {area_reg_polygon(3, 10) = }")
547582
print(f"Square: {area_reg_polygon(4, 10) = }")
548583
print(f"Reqular Pentagon: {area_reg_polygon(5, 10) = }")

0 commit comments

Comments
 (0)