import random
# Define parameters
POPULATION_SIZE = 10 # Number of individuals in the population
CHROMOSOME_LENGTH = 5 # Number of bits in the chromosome (since 2^5=32>31)
GENERATIONS = 20 # Number of generations to evolve
MUTATION_RATE = 0.01 # Probability of mutation
# Fitness function
def fitness(x):
return x ** 2
# Decode binary chromosome to integer
def decode(chromosome):
return int(chromosome, 2)
# Initialize population with random chromosomes
def initialize_population():
population = []
for _ in range(POPULATION_SIZE):
chromosome = ''.join(random.choice(['0', '1']) for _ in range(CHROMOSOME_LENGTH))
population.append(chromosome)
return population
# Selection: roulette wheel selection
def select_pair(population, fitnesses):
total_fitness = sum(fitnesses)
pick = random.uniform(0, total_fitness)
current = 0
for chromosome, fit in zip(population, fitnesses):
current += fit
if current > pick:
return chromosome
return population[-1]
# Crossover: single-point crossover
def crossover(parent1, parent2):
if CHROMOSOME_LENGTH < 2:
return parent1, parent2
point = random.randint(1, CHROMOSOME_LENGTH - 1)
child1 = parent1[:point] + parent2[point:]
child2 = parent2[:point] + parent1[point:]
return child1, child2
# Mutation: flip a bit with probability MUTATION_RATE
def mutate(chromosome):
mutated = ''
for bit in chromosome:
if random.random() < MUTATION_RATE:
mutated += '1' if bit == '0' else '0'
else:
mutated += bit
return mutated
def genetic_algorithm():
# Initialize population
population = initialize_population()
for generation in range(GENERATIONS):
# Decode population and calculate fitness
decoded = [decode(chrom) for chrom in population]
fitnesses = [fitness(x) for x in decoded]
print(f"Generation {generation}: Max Fitness = {max(fitnesses)} (x = {decoded[fitnesses.index(max(fitnesses))]})")
# Create new population
new_population = []
while len(new_population) < POPULATION_SIZE:
# Selection
parent1 = select_pair(population, fitnesses)
parent2 = select_pair(population, fitnesses)
# Crossover
child1, child2 = crossover(parent1, parent2)
# Mutation
child1 = mutate(child1)
child2 = mutate(child2)
# Add to new population
new_population.extend([child1, child2])
# If population size is odd, remove one excess individual
if len(new_population) > POPULATION_SIZE:
new_population.pop()
population = new_population
# Final result
decoded = [decode(chrom) for chrom in population]
fitnesses = [fitness(x) for x in decoded]
max_fit = max(fitnesses)
best_x = decoded[fitnesses.index(max_fit)]
print(f"\nBest solution: x = {best_x}, f(x) = {max_fit}")
if __name__ == "__main__":
genetic_algorithm()
When you run the above code, you’ll see output similar to the following, showing the progression of the maximum fitness over generations:
Note: Since the function ( f(x) = x^2 ) is maximized at the upper boundary of the range (i.e., ( x = 31 )), in this example with small population size and limited generations, the GA might not reach the global maximum. To achieve better results:
This simple example demonstrates the core components of a genetic algorithm: initialization, fitness evaluation, selection, crossover, mutation, and replacement. GAs are versatile and can be adapted to solve a wide range of optimization and search problems, from scheduling and machine learning to engineering design and beyond.