I'm trying to implement a simple genetic algorithm in Python to maximize the function f(x) = x²
for x
in the range [0, 31]
. I'm using binary encoding for chromosomes (each chromosome is a 5-bit binary string).
Here's what I have so far:
import random
# Fitness function: square of x
def fitness(x):
return x * x
# Convert integer to 5-bit binary string (chromosome)
def to_binary(x):
return format(x, '05b')
# Initialize population (6 random individuals)
population = [random.randint(0, 31) for _ in range(6)]
# Run for 5 generations
for gen in range(5):
# Sort by fitness (higher is better)
population.sort(key=fitness, reverse=True)
# Print generation info
print(f"Gen {gen}: {[to_binary(x) for x in population]} | Raw: {population}")
# Selection: Keep top 2, add 4 new random individuals
population = population[:2] + [random.randint(0, 31) for _ in range(4)]