# Consider the following fitness function
fn <- function(x)
{
val <- x[1] * x[2] - x[1] ^ 2 - x[2] ^ 2
}
# Also let's provide it's gradient (optional)
gr <- function(x)
{
val <- c(x[2] - 2 * x[1],
x[1] - 2 * x[2])
}
# Randomly initialize the population
set.seed(123)
n_population <- 10
population <- gena.population(pop.n = n_population,
lower = c(-5, -5),
upper = c(5, 5))
# Calculate fitness of each chromosome
fitness <- rep(NA, n_population)
for(i in 1:n_population)
{
fitness[i] <- fn(population[i, ])
}
# Perform hybridization
hybrids <- gena.hybrid(population = population,
fitness = fitness,
opt.par = list(fn = fn,
gr = gr,
method = "BFGS",
control = list(fnscale = -1,
abstol = 1e-10,
reltol = 1e-10,
maxit = 1000)),
hybrid.n = 2,
method = "rank",
par = 0.8)
print(hybrids)
Run the code above in your browser using DataLab