I am trying to estimate a set of parameters using a genetic algorithm in R with the 'GA' package. So far I am doing something very simple (which works):

df <- data.frame(DM=c(1000,1500),

func <- function(x1, x2, theta) theta[1]*x1 + theta[2]*x2
fitnessL2 <- function(theta, x1, x2, y) {
              f <- -sum((y - func(x1, x2, theta))^2)
GA2 <- ga(type = "real-valued", fitness = fitnessL2,
          x1 = df$c1, x2 = df$c2, y = df$DM, names = c("a", "b"), 
          min = c(0, 0), max = c(100, 100))

which produces values for a,b. However, I want to constrain a and b not individually, but as something like a + b == 20.

Can someone please let me know if this is possible?

Thanks in advance.


1 Answer 1


If you have $a+b=20$, you have only one parameter, say $a$; the second is just $20-a$. This way you only need to tweak the function a bit and you are left with a single, simple constraint over $a$.

  • $\begingroup$ Thanks, but in reality I have something with about 20 parameters so more like A+B+C+D+E.... = 20. I need to know if this situation is possible. $\endgroup$
    – mike1886
    Feb 11, 2014 at 14:05
  • $\begingroup$ Ok, it is hard to tell without the full knowledge of what constraints do you have, but it still holds that it is better to use the constraint to simplify the fitness function than to limit the search to some crazy subspace. Even if this is impossible, there is still an option to make a "smooth constraint", i.e. add something like $A\cdot C(\mathbf{p})^2$ to your fitness, where $C(\mathbf{p})=0$ is your problematic constraint, $\mathbf{p}$ are the parameters and $A$ is something that makes this term larger than the fitness deviations near the optimum. $\endgroup$
    – user88
    Feb 11, 2014 at 14:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.