Fractal geometry (Menger sponge)
- Peter Mortier
- Mar 9
- 2 min read
Updated: 1 day ago
Fractal geometry is a branch of mathematics that explores self-similar patterns that repeat at different scales, often displaying intricate complexity regardless of magnification. Unlike traditional Euclidean geometry, which relies on simple shapes like circles, squares, and triangles, fractals are defined by recursive algorithms that generate infinitely detailed structures. They are found both in nature - such as in the branching of trees, and the structure of snowflakes - and in artificial constructs like computer-generated fractals.
The Menger sponge (also called Sierpinski cube) is a classic example of a three-dimensional fractal, constructed by recursively removing smaller cubes from a larger cube in a systematic manner. Starting with a solid cube, each iteration divides the cube into 27 smaller cubes, removing the central cube and the centers of each face, leaving a structure full of voids. As this process continues infinitely, the Menger sponge approaches an infinite surface area yet zero volume. This fractal serves as an important mathematical model in topology and geometry, demonstrating extreme porosity.
The example below shows how to create the Menger sponge using HelloTriangle. There are a few methods used that we will briefly explain:
Test: This flags elements having nodal coordinates between min and max in the specific direction (dir=0 is the X direction, dir=1 is the Y direction and dir=2 is the Z direction). This method returns an array with boolean values (True or False).
Cclip: This returns a Mesh with the selected elements removed. If you want to do the opposite, i.e. return a Mesh with only the selected elements, use the clip method.
If you are interested in 3D fractals, you may also want to take a look at our Sierpinski tetrahedron example.
from hellotriangle import shapes
def fractal(cube, level=3):
"""Function to generate Menger sponge."""
while level > 0:
# create a cube that consists of 27 smaller cubes
cubes = cube.replicateXYZ(n=[3,3,3], step=[1.0, 1.0, 1.0])
# scale to obtain a cube with edge length 1
cube = cubes.scale(0.3333333)
# parameters to remove cubes in the center
min = 1.0/3.0 - 0.0001
max = 2.0/3.0 + 0.0001
# find and remove cubes in the center
testX = cube.test(dir = 0, min = min, max = max)
testY = cube.test(dir = 1, min = min, max = max)
testZ = cube.test(dir = 2, min = min, max = max)
cube = cube.cclip(testX*testY + testX*testZ + testZ*testY)
# adjust level
level = level-1
return cube
# generate basic cube
cube = shapes.cube(eltype='hex8')
# generate fractal geometry
sponge = fractal(cube,level=3)
# draw
draw(sponge, color = "#D62246")



