Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- # Definindo os parâmetros
- num_bits = 8
- individuos = 4
- taxa_mutacao = 0.01
- taxa_crossover = 0.7
- num_geracoes = 5
- # Definindo a função objetivo
- def fitness(x):
- return x**2 - 3*x + 4
- # Função para converter de binário para decimal
- def decode(binary):
- return int(''.join(binary), 2) / (2**num_bits - 1) * 20 - 10
- # Função de mutação
- def mutate(individual):
- for i in range(num_bits):
- if random.random() < taxa_mutacao:
- individual[i] = '1' if individual[i] == '0' else '0'
- return individual
- # Função de crossover
- def crossover(parent1, parent2):
- if random.random() < taxa_crossover:
- crossover_point = random.randint(1, num_bits - 1)
- child1 = parent1[:crossover_point] + parent2[crossover_point:]
- child2 = parent2[:crossover_point] + parent1[crossover_point:]
- return child1, child2
- else:
- return parent1, parent2
- # Função de seleção por torneio
- def tournament_selection(population):
- tournament_size = 2
- tournament = random.sample(population, tournament_size)
- tournament.sort(key=lambda x: fitness(decode(x)), reverse=True)
- return tournament[0]
- # Inicializando a população
- population = [''.join(random.choice(['0', '1']) for _ in range(num_bits)) for _ in range(individuos)]
- # Loop de gerações
- for generation in range(num_geracoes):
- new_population = []
- for _ in range(individuos // 2):
- parent1 = tournament_selection(population)
- parent2 = tournament_selection(population)
- child1, child2 = crossover(parent1, parent2)
- child1 = mutate(list(child1))
- child2 = mutate(list(child2))
- new_population.extend([child1, child2])
- population = new_population
- # Encontrando o melhor indivíduo
- best_individual = max(population, key=lambda x: fitness(decode(x)))
- # Decodificando o melhor indivíduo para obter o valor de x
- x = decode(best_individual)
- max_value = fitness(x)
- print(f'O valor de x que maximiza a função é aproximadamente {x:.4f} e o valor máximo é aproximadamente {max_value:.4f}.')
Advertisement
Add Comment
Please, Sign In to add comment