Sierpinski Triangle with R

Sierpinski Triangle
Sierpinski Triangle


In this post, I present an R script for drawing the Sierpinski Triangle. Here is the algorithm:

  1. Define three points (A, B, and C) of the triangle.
  2. Select a random 2D point, say it base. Draw it.
  3. Pick one point randomly from the set {A, B, C}, say it lucky edge.
  4. Draw a line segment between base and lucky edge, pick the point at the middle of the line segment, this is the new base.
  5. Repeat step 3 and step 4 many times.

Here is the R code with the comments.

# Number of points
POINTSIZE <- 10000;

# Matrix for the generated points
mypoints <- matrix(0, nrow = POINTSIZE, ncol=2)

# Edges of the triangle
A <- c(500, 1000)
B <- c(0,0)
C <- c(1000,0)
edgeSet <- list(A, B, C)

# Starter point. It can be selected randomly
newpoint <- c(20, 40)

# Main loop
for (i in 1:POINTSIZE){
  r <- runif(1)
  lucky <- unlist(sample(edgeSet, 1))
  newpoint <- c((lucky[1] + newpoint[1])/2, (lucky[2] + newpoint[2])/2)
  mypoints[i,] <- newpoint

# Plotting
plot.window(xlim=c(0,1000), ylim=c(0,1000))
points(mypoints, pch=2, col = topo.colors(255))

In this code, the variable POINTSIZE defines the number of points. The generated points are stored in the 2D matrix mypoints. At each step of the algorithm, a randomly point of the triangle is selected and stored in the variable lucky. Then the variable newpoint is generated by calculating middle of the line segment which is mentioned as base in the algorithm.

Sierpinski Triangle with colors
Sierpinski Triangle with colors

The line

plot.window(xlim=c(0,1000), ylim=c(0,1000))

can be changed to

points(mypoints, pch=".", col = topo.colors(255))

for colored output. By changing the pch = "." parameter, plot character can be changed:

points(mypoints, pch=2, col = topo.colors(255))

Hope you have fun 🙂