Graphing Rastrigin’s Function in 3D Color Gradient using R

Rastrigin’s function is a math function that is often used as a benchmark problem to evaluate the effectiveness of numerical optimization algorithms. The function has a known minimum value of 0.0 at (0, 0, . . 0) where the number of zero values is equal to the dimension of the function. For example, if the dimension is set to 2, then the minimum value of Rastrigin’s function is at (0, 0).


Rastrigin’s function is difficult to solve because it has many peaks and valleys that represent local minimum values that can trap an algorithm.

I often work with Rastrigin’s function and so I sometimes find it useful to create a graph of it. My current method of choice for creating 3D graphs is to use the R language.

The commands I used start with:

# CTRL-L clears the shell
rm(list=ls()) # delete all objects
x0 <- seq(-5.12, 5.12, length=100)
x1 <- seq(-5.12, 5.12, length=100)
f <- function(x0, x1) { 20 + (x0^2 - 10 *
 cos(2 * 3.14 *x0)) + (x1^2 - 10 *
 cos(2 * 3.14 *x1)) }
z <- outer(x0, x1, f)

After deleting all existing objects in the R workspace, I set up arrays x0 and x1 with 100 values evenly spaced between -5.12 and +5.12 (standard ranges for Rastrigin’s function). The next command defines Rastrigin’s function. The hard-coded 20 is actually 2 * 10 where the 2 is because I have Rastrigin’s function with dim = 2 (x0 and x1).


jet.colors <- colorRampPalette(c("midnightblue",
 "blue", "cyan", "green", "yellow", "orange",
 "red", "darkred"))
nbcol <- 64
color <- jet.colors(nbcol)
nrz <- nrow(z)
ncz <- ncol(z)

zfacet <- z[-1,-1] + z[-1,-ncz] +
 z[-nrz,-1] + z[-nrz,-ncz]
facetcol <- cut(zfacet, nbcol)

I set up a custom color gradient from dark blue to dark red. You can think of the zfacet and facetcol as magic R incantations for doing a 3D color gradient graph.

The graph is created with:

persp(x0, x1, z, col=color[facetcol],
 phi=15, theta=-35, ticktype="detailed",
 d=10, r=1, shade=0.1, expand=0.7)

The phi argument is the tilt-the-base angle. The theta is the rotate-the-base angle. The d is the perspective effect; larger d lessens effect. The r is distance-to-eye. The expand shrinks the plotting box when d < 1. There are several other parameters you can use too.

This entry was posted in Machine Learning. Bookmark the permalink.