Skip to content

Commit 4eb5c12

Browse files
Sphere intersection and spherical cap volumes (#5579)
* sphere intersection + spherical cap volume formulas * reformatted * Update volume.py Co-authored-by: Christian Clauss <[email protected]>
1 parent 9a03919 commit 4eb5c12

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

maths/volume.py

+52
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,56 @@ def vol_cube(side_length: int | float) -> float:
2020
return pow(side_length, 3)
2121

2222

23+
def vol_spherical_cap(height: float, radius: float) -> float:
24+
"""
25+
Calculate the Volume of the spherical cap.
26+
:return 1/3 pi * height ^ 2 * (3 * radius - height)
27+
28+
>>> vol_spherical_cap(1, 2)
29+
5.235987755982988
30+
"""
31+
return 1 / 3 * pi * pow(height, 2) * (3 * radius - height)
32+
33+
34+
def vol_spheres_intersect(
35+
radius_1: float, radius_2: float, centers_distance: float
36+
) -> float:
37+
"""
38+
Calculate the volume of the intersection of two spheres.
39+
40+
The intersection is composed by two spherical caps and therefore its volume is the
41+
sum of the volumes of the spherical caps. First it calculates the heights (h1, h2)
42+
of the the spherical caps, then the two volumes and it returns the sum.
43+
The height formulas are
44+
h1 = (radius_1 - radius_2 + centers_distance)
45+
* (radius_1 + radius_2 - centers_distance)
46+
/ (2 * centers_distance)
47+
h2 = (radius_2 - radius_1 + centers_distance)
48+
* (radius_2 + radius_1 - centers_distance)
49+
/ (2 * centers_distance)
50+
if centers_distance is 0 then it returns the volume of the smallers sphere
51+
:return vol_spherical_cap(h1, radius_2) + vol_spherical_cap(h2, radius_1)
52+
53+
>>> vol_spheres_intersect(2, 2, 1)
54+
21.205750411731103
55+
"""
56+
if centers_distance == 0:
57+
return vol_sphere(min(radius_1, radius_2))
58+
59+
h1 = (
60+
(radius_1 - radius_2 + centers_distance)
61+
* (radius_1 + radius_2 - centers_distance)
62+
/ (2 * centers_distance)
63+
)
64+
h2 = (
65+
(radius_2 - radius_1 + centers_distance)
66+
* (radius_2 + radius_1 - centers_distance)
67+
/ (2 * centers_distance)
68+
)
69+
70+
return vol_spherical_cap(h1, radius_2) + vol_spherical_cap(h2, radius_1)
71+
72+
2373
def vol_cuboid(width: float, height: float, length: float) -> float:
2474
"""
2575
Calculate the Volume of a Cuboid.
@@ -127,6 +177,8 @@ def main():
127177
print("Pyramid: " + str(vol_pyramid(2, 2))) # ~= 1.33
128178
print("Sphere: " + str(vol_sphere(2))) # ~= 33.5
129179
print("Circular Cylinder: " + str(vol_circular_cylinder(2, 2))) # ~= 25.1
180+
print("Spherical cap: " + str(vol_spherical_cap(1, 2))) # ~= 5.24
181+
print("Spheres intersetion: " + str(vol_spheres_intersect(2, 2, 1))) # ~= 21.21
130182

131183

132184
if __name__ == "__main__":

0 commit comments

Comments
 (0)