Genetic Algorithms for Function Optimization

One Dimension
library('GA') f <- function(x) abs(x) + cos(x) min <- -20 max <- +20 curve(f, min, max) fitness <- function(x) -f(x) GA <- ga(type = "real-valued", fitness = fitness, min = min, max = max) GA plot(GA) summary(GA) The code is quite intuitive and the GA will give output as follows: +---+ |        Genetic Algorithm         | +---+ GA settings: Type                 =  real-valued Population size      =  50 Number of generations = 100 Elitism              =  2 Crossover probability = 0.8 Mutation probability =  0.1 Search domain x1 Min -20 Max 20 GA results: Iterations            = 100 Fitness function value = -1.000026 Solution              = x1 [1,] -2.558151e-05

Two Dimension
We could apply to do two dimensional function approximation. Even higher dimension is okay. The function we are using is plotted in the right. Rastrigin <- function(x1, x2) {    d = 2 sum <- x1^2 + x2^2- 10*cos(2*pi*x1) - 10*cos(2*pi*x2) y <- 10*d + sum return(y) } x1 <- x2 <- seq(-5.12, 5.12, by = 0.1) f <- outer(x1, x2, Rastrigin) persp3D(x1, x2, f, theta = 50, phi = 20) filled.contour(x1, x2, f, color.palette = jet.colors) GA <- ga(type = "real-valued",         fitness = function(x) -Rastrigin(x[1], x[2]),          min = c(-5.12, -5.12), max = c(5.12, 5.12), popSize = 50,          maxiter = 100) summary(GA) The result for the before code is +---+ |        Genetic Algorithm         | +---+ GA settings: Type                 =  real-valued Population size      =  50 Number of generations = 100 Elitism              =  2 Crossover probability = 0.8 Mutation probability =  0.1 Search domain x1   x2 Min -5.12 -5.12 Max 5.12  5.12 GA results: Iterations            = 100 Fitness function value = -8.808823e-08 Solution              = x1          x2 [1,] -9.501309e-06 1.880787e-05

More to try out!
This is great pdf introducing GA algorithmhttp://www.jstatsoft.org/v53/i04/paper