Graphing Rastrigin’s Function using the R Language

Rastrigin’s function is a standard benchmark used to test the effectiveness of numerical optimization algorithms. The R language is used most often for statistical kinds of work. The R language and environment are somewhat similar to MatLab, however R is open source and MatLab is very pricey (in my opinion).

R has been around since the mid-1990s. I don’t use R very often. I was surprised when Microsoft acquired the Revolution Analytics company in January 2015. RA focuses mainly on integrating R with Hadoop. Anyway, the acquisition means that R is now an informal part of the Microsoft technologies ecosystem.


So, I decided to dust off my R and take a look at the most recent version. I installed R and decided to generate a 3D surface plot of Rastrigin’s function. The R commands I used were:

1. x<-seq(-5.12,5.12,length=100)

2. y<-x

3. f<-function(x,y) { 20+(x^2-10*cos(2*3.14*x))+
   (y^2-10*cos(2*3.14*y)) }

4. z<-outer(x,y,f)

5. z[]<-1

6. persp(x,y,z,theta=30,phi=30,expand=0.5,col="red",

The first command sets up an array named x with 100 values ranging from -5.12 to +5.12. The second command makes a copy of the x values in a new array named y. The third statement defines a function f which implements Rastrigin’s function. The fourth statement uses the built-in outer function, which accepts two arrays and a function, to generate a matrix named z. The fifth statement is loosely, “if any value in matrix z is not available, put a value of 1 there.”

The sixth statement, calls the persp (“perspective plot”) to generate the 3D graph. The persp function has a zillion parameters and I only used a few.

I can’t say I’m a huge fan of either R or MatLab. However, they are both very nice when I need to create a 3D graph. The main weakness with R graphs is that it takes a little bit extra effort to make a color gradient. Notice the graph is all red which makes some of the hills and valleys hard to see. I’ll show how to do a color gradient surface plot version of Rastrigin’s function in another post.

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