Solving problems with genetic algorithms
How genetic algorithms (GAs) encode candidate solutions, evolve a population with selection, crossover and mutation, and are used to solve optimisation and search problems in engineering.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Genetic algorithms (GAs) are search and optimisation methods inspired by natural evolution. Engineers use GAs when the search space is large, multimodal or not smooth (no easy gradient), for example in circuit placement, scheduling, parameter tuning of controllers, or design optimization where classical methods fail.
Key ideas
Start with simple definitions (each bolded term is defined when first used).
- Genetic algorithm (GA): a population-based stochastic search algorithm that iteratively applies selection, crossover and mutation to a set of encoded candidate solutions (the population) to find high-fitness solutions to an optimisation or search problem.
- Population: a set of candidate solutions (individuals) maintained at each generation. Each individual is represented by a chromosome.
- Chromosome / genotype: the encoded representation (often a string of bits or numbers) of a candidate solution. The mapping from genotype to a real-world solution is called phenotype mapping or decoding.
- Fitness function: a scalar function that assigns a fitness value to an individual based on its phenotype; higher fitness usually means better solution.
- Selection: process to choose parents from the population with probability related to fitness (creates selection pressure). Examples: fitness-proportionate (roulette-wheel) selection, tournament selection, rank selection.
- Crossover (recombination): operator that combines genetic material from two parents to produce offspring. Examples: one-point, two-point, uniform crossover. For permutation encoding, use order-preserving crossovers (e.g., PMX, OX, CX) and swap/inversion mutation to maintain valid permutations.
- Mutation: operator that randomly alters bits/genes to introduce diversity (e.g., bit-flip mutation for binary encoding, Gaussian perturbation for real-encoding).
- Elitism: copying best individuals unchanged to next generation to preserve best found solutions.
- Encoding types: binary encoding (bit-strings), real-valued encoding (direct floating-point genes), permutation encoding (for ordering problems like TSP). Choose encoding to match the problem structure.
- Termination criteria: a fixed number of generations, no improvement over many generations, or reaching a desired fitness.
Important theoretical result often required in exams:
Schema: a schema H over binary strings of length l is a pattern using symbols {0,1,}, where * is a “don’t care”. Example: 10* describes all 4-bit strings with 1 as first bit and 0 as third bit. Define the order o(H) as number of fixed positions (non-*), and the defining length δ(H) as distance between the first and last fixed positions (index difference).
Holland’s Schema Theorem (informal exact statement students must remember): Let m(H,t) be the number of individuals in generation t that match schema H. Let f(H) be the average fitness of those individuals, and let f̄ be the average fitness of the whole population. If selection is fitness-proportionate, and crossover probability is pc and per-bit mutation probability is pm, then the expected number in the next generation satisfies (lower bound):
E[m(H,t+1)] ≥ m(H,t) * (f(H)/f̄) * (1 - pc * (δ(H)/(l-1)) - pm * o(H)).
Assumptions: binary encoding, fitness-proportionate selection, single-point crossover, independent low-rate mutation, and small probabilities (so higher order joint effects neglected). This is a bound (not exact) showing short, low-order, above-average fitness schemata increase exponentially.
Derivation sketch (what examiners expect):
- After selection only (no crossover/mutation), expected copies due to selection: m(H,t) * (f(H)/f̄).
- Consider probability that schema H is disrupted by single-point crossover: for single-point crossover, a cut between positions i and i+1 breaks H iff cut lies between first and last fixed positions; there are (l-1) possible cut points and δ(H) of them are damaging, so disruption probability ≈ pc * (δ(H)/(l-1)). Survival factor from crossover ≈ 1 - pc * (δ(H)/(l-1)).
- Mutation flips any of the o(H) fixed bits with probability pm each; survival factor from mutation ≈ (1 - pm)^{o(H)} ≈ 1 - pm * o(H) for small pm.
- Multiply selection expectation by both survival factors to get the stated bound.
What to draw (diagram) in an exam: Draw a population of simple bit-strings (e.g., four 6-bit chromosomes), highlight those matching schema H (use shading), draw one-point crossover location options on a line of bit positions 1..l, mark δ(H) region between first and last fixed positions, label l, δ(H), o(H). This visual helps explain crossover disruption probability.
Practical notes: Choose encoding to exploit problem structure (e.g., permutation encoding for ordering). Choose selection to control pressure (tournament selection with small tournament size gives moderate pressure). Use elitism to avoid losing best solutions. Also decide a replacement strategy (generational vs steady-state) and how to handle constraints (penalty functions or repair).
Formulas
p_i = f_i / sum_{j=1..N} f_j — probability individual i is selected under fitness-proportionate selection; f_i is fitness (unitless), N is population size; applies when all fitness values are non-negative.
E[m(H,t+1)] >= m(H,t) * (f(H)/f̄) * (1 - pc * (δ(H)/(l-1)) - pm * o(H)) — schema theorem lower bound; m(H,t) is count of schema H at generation t (unitless), f(H) average fitness of those, f̄ average population fitness, pc crossover probability (0..1), δ(H) defining length (positions), l chromosome length (positions), pm mutation probability per bit (0..1), o(H) order of schema (integer).
P_survive_crossover ≈ 1 - pc * (δ(H)/(l-1)) — approximate probability a schema survives single-point crossover; applies for single-point crossover.
P_survive_mutation ≈ (1 - pm)^{o(H)} ≈ 1 - pm * o(H) for small pm — probability schema survives mutation; pm is mutation probability per gene.
expected_offspring_count_after_selection = m(H,t) * (f(H)/f̄) — selection expectation only.
binary_to_real = a + (b - a) * value(binary) / (2^l - 1) — decoding k-bit binary to real in range [a,b]; value(binary) integer value, l=k bits.
Worked examples
Example 1 — hand computation (university exam style) Problem: Maximise f(x)=x^2 for integer x in [0,7]. Use 3-bit binary encoding (l=3). Initial population of 4 individuals (generation 0): 001, 010, 101, 111. Use roulette-wheel selection, single-point crossover pc=0.7, mutation pm=0.01 (low, neglect mutation effect in one step), no elitism. Compute one generation.
Step 1: decode and fitness (f=x^2)
- 001 -> x=1 -> f=1
- 010 -> x=2 -> f=4
- 101 -> x=5 -> f=25
- 111 -> x=7 -> f=49 Sum f = 1+4+25+49 = 79, average f̄ = 79/4 = 19.75
Step 2: selection probabilities p_i = f_i / 79
- p1=1/79 ≈ 0.0127
- p2=4/79 ≈ 0.0506
- p3=25/79 ≈ 0.3165
- p4=49/79 ≈ 0.6203
Step 3: expected copies after selection = m(H,t)*(f(H)/f̄) for any schema. For whole individuals, expected counts = N * p_i = 4 * p_i
- E1 ≈ 4 * 0.0127 = 0.0508
- E2 ≈ 4 * 0.0506 = 0.2024
- E3 ≈ 4 * 0.3165 = 1.266
- E4 ≈ 4 * 0.6203 = 2.481 (So likely two copies of 111, one of 101, others rare.)
Step 4: apply crossover (pc=0.7). With high probability parents 111 and 101 will produce offspring similar to best parent. Because pm small, mutation ignored here. Final generation likely contains individuals near x=7 and x=5. (In an exam, justify with probabilities and expected numbers; you can show one possible sampled outcome.)
Final answer (bold): After one generation selection strongly favours 111 and 101; expected counts ~2.48 and ~1.27 respectively, so population moves toward higher x values; best individual expected to remain 111.
Example 2 — Python program (complete, deterministic by fixed seed) Problem: Use a simple GA to maximise f(x)=x * sin(10pix) + 1 over x in [0,1] with binary encoding of 16 bits. Print best solution after 100 generations.
Code (run with Python 3):
import random, math
random.seed(42)
# GA parameters
POP = 50
L = 16 # bits
GEN = 100
PC = 0.7
PM = 1.0 / L
def decode(bits):
val = int(''.join(bits), 2)
return val / (2**L - 1)
def fitness(bits):
x = decode(bits)
return x * math.sin(10 * math.pi * x) + 1
# init
pop = [[random.choice('01') for _ in range(L)] for _ in range(POP)]
for g in range(GEN):
fits = [fitness(ind) for ind in pop]
# elitism: keep best
best_idx = fits.index(max(fits))
newpop = [pop[best_idx][:]]
# selection: roulette
total = sum(fits)
probs = [f / total for f in fits]
cum = []
s = 0
for p in probs:
s += p; cum.append(s)
def select_one():
r = random.random()
for i,c in enumerate(cum):
if r <= c: return [b for b in pop[i]]
return [b for b in pop[-1]]
while len(newpop) < POP:
# parents
p1 = select_one(); p2 = select_one()
# crossover
if random.random() < PC:
pt = random.randint(1, L-1)
c1 = p1[:pt] + p2[pt:]
c2 = p2[:pt] + p1[pt:]
else:
c1, c2 = p1[:], p2[:]
# mutation
for child in (c1, c2):
for i in range(L):
if random.random() < PM:
child[i] = '1' if child[i] == '0' else '0'
if len(newpop) < POP:
newpop.append(child)
pop = newpop[:POP]
# final best
fits = [fitness(ind) for ind in pop]
best = pop[fits.index(max(fits))]
x = decode(best)
print(f"best x = {x:.6f}, fitness = {max(fits):.6f}, binary = {''.join(best)}")
Sample output is deterministic for a given Python version when random.seed(42) is set; run the code to obtain the exact numbers on your machine.
Common mistakes
- Miscomputing defining length δ(H): it is index(last fixed) - index(first fixed), not number of fixed bits.
- Ignoring elitism: students forget to state whether best individual is preserved.
- Applying schema theorem as equality rather than a lower bound and forgetting assumptions (single-point crossover, small pm).
- Using high mutation/crossover without discussing exploration vs exploitation and effects on convergence.
- Not fixing random seed when demonstrating code in answers; then sample outputs differ.
For your exam
Typical question types:
- Definitions: define GA, schema, fitness, selection operators, crossover types.
- Short notes: explain encoding choices, selection pressure, elitism, advantages/limitations of GAs.
- Derivations: derive the schema theorem bound step-by-step (must show selection term, crossover disruption, mutation survival). Show diagram of bit positions and cut points.
- Numericals: small population example with binary encoding; perform one or two generations (decode, compute fitness, selection probabilities, apply crossover/mutation). Show arithmetic clearly and units (fitness unitless).
- Programs: write a simple GA (Python/pseudocode) to optimise a function or match a target string; mention fixed seed for deterministic output.
What full-marks answers include:
- Clear definitions with bold terms, assumptions stated.
- Correct formulas with all symbols defined.
- Step-by-step derivations and explicit probability calculations.
- If asked, draw/describe diagrams (population, bit positions, crossover points) and label l, δ(H), o(H).
- Correct final numerical values or runnable code with sample output.
Quick check
- What is the difference between genotype and phenotype?
- Write the formula for selection probability under roulette-wheel selection.
- In Holland’s schema theorem, how does a larger defining length δ(H) affect survival probability under single-point crossover?
Answers: 1. Genotype is the encoded representation (bit-string etc.), phenotype is the decoded actual solution in problem domain. 2. p_i = f_i / sum_j f_j. 3. Larger δ(H) increases chance of being cut by crossover, so survival probability decreases (disruption probability proportional to δ(H)/(l-1)).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?