biaft03

ia

Oct 18th, 2023
826
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.11 KB | None | 0 0
  1. import random
  2.  
  3. # Definindo os parâmetros
  4. num_bits = 8
  5. individuos = 4
  6. taxa_mutacao = 0.01
  7. taxa_crossover = 0.7
  8. num_geracoes = 5
  9.  
  10.  
  11. # Definindo a função objetivo
  12. def fitness(x):
  13.     return x**2 - 3*x + 4
  14.  
  15.  
  16. # Função para converter de binário para decimal
  17. def decode(binary):
  18.     return int(''.join(binary), 2) / (2**num_bits - 1) * 20 - 10
  19.  
  20.  
  21. # Função de mutação
  22. def mutate(individual):
  23.     for i in range(num_bits):
  24.         if random.random() < taxa_mutacao:
  25.             individual[i] = '1' if individual[i] == '0' else '0'
  26.     return individual
  27.  
  28.  
  29. # Função de crossover
  30. def crossover(parent1, parent2):
  31.     if random.random() < taxa_crossover:
  32.         crossover_point = random.randint(1, num_bits - 1)
  33.         child1 = parent1[:crossover_point] + parent2[crossover_point:]
  34.         child2 = parent2[:crossover_point] + parent1[crossover_point:]
  35.         return child1, child2
  36.     else:
  37.         return parent1, parent2
  38.  
  39.  
  40. # Função de seleção por torneio
  41. def tournament_selection(population):
  42.     tournament_size = 2
  43.     tournament = random.sample(population, tournament_size)
  44.     tournament.sort(key=lambda x: fitness(decode(x)), reverse=True)
  45.     return tournament[0]
  46.  
  47.  
  48. # Inicializando a população
  49. population = [''.join(random.choice(['0', '1']) for _ in range(num_bits)) for _ in range(individuos)]
  50.  
  51. # Loop de gerações
  52. for generation in range(num_geracoes):
  53.     new_population = []
  54.     for _ in range(individuos // 2):
  55.         parent1 = tournament_selection(population)
  56.         parent2 = tournament_selection(population)
  57.         child1, child2 = crossover(parent1, parent2)
  58.         child1 = mutate(list(child1))
  59.         child2 = mutate(list(child2))
  60.         new_population.extend([child1, child2])
  61.     population = new_population
  62.  
  63. # Encontrando o melhor indivíduo
  64. best_individual = max(population, key=lambda x: fitness(decode(x)))
  65.  
  66. # Decodificando o melhor indivíduo para obter o valor de x
  67. x = decode(best_individual)
  68. max_value = fitness(x)
  69.  
  70. print(f'O valor de x que maximiza a função é aproximadamente {x:.4f} e o valor máximo é aproximadamente {max_value:.4f}.')
  71.  
Advertisement
Add Comment
Please, Sign In to add comment