79590808

Date: 2025-04-24 14:17:45
Score: 0.5
Natty:
Report link

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)]
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Prito