Programming Problem:
Problem Statement:
Use a Genetic Algorithm to maximize the function:
f(x)=x2where 0≤x≤31f(x) = x^2 \quad \text{where } 0 \leq x \leq 31f(x)=x2where 0≤x≤31
• Represent xxx as a 5-bit binary string.
• Population size = 6
• Number of generations = 10
Sample Python code
import random
# Fitness function: f(x) = x^2
def fitness(x):
return x**2
# Convert binary string to integer
def decode(binary):
return int(binary, 2)
# Generate random binary chromosome
def random_chromosome(length=5):
return ''.join([Link]('01') for _ in range(length))
# Selection: Roulette Wheel
def selection(population):
total_fitness = sum(fitness(decode(ch)) for ch in population)
pick = [Link](0, total_fitness)
current = 0
for ch in population:
current += fitness(decode(ch))
if current >= pick:
return ch
# Crossover: Single-point
def crossover(parent1, parent2):
point = [Link](1, len(parent1)-1)
child1 = parent1[:point] + parent2[point:]
child2 = parent2[:point] + parent1[point:]
return child1, child2
# Mutation: Bit flip
def mutate(chromosome, mutation_rate=0.1):
return ''.join(
bit if [Link]() > mutation_rate else '1' if bit == '0' else '0'
for bit in chromosome
# Genetic Algorithm
def genetic_algorithm(generations=10, pop_size=6, chrom_length=5):
# Initial population
population = [random_chromosome(chrom_length) for _ in range(pop_size)]
for gen in range(generations):
new_population = []
for _ in range(pop_size // 2):
# Selection
parent1 = selection(population)
parent2 = selection(population)
# Crossover
child1, child2 = crossover(parent1, parent2)
# Mutation
child1 = mutate(child1)
child2 = mutate(child2)
new_population.extend([child1, child2])
population = new_population
best = max(population, key=lambda ch: fitness(decode(ch)))
print(f"Generation {gen+1}: Best = {best} (x={decode(best)}, f(x)={fitness(decode(best))})")
return best
# Run GA
best_solution = genetic_algorithm()
print("\nBest solution found:", best_solution, "Value of x:", decode(best_solution), "Fitness:",
fitness(decode(best_solution)))