Advertisement
EduPsEudo

Raizes - Evolucionário v2

Aug 16th, 2023
1,039
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.20 KB | None | 0 0
  1. import random
  2. import math
  3.  
  4. SIZE = 100
  5. N_REP = 100
  6.  
  7. EQ = {'a': 1, 'b': -7, 'c': 0} # ax² + bx + c
  8.  
  9. def delta(eq):
  10.     return pow(eq['b'], 2) - (4 * eq['a'] * eq['c'])
  11.  
  12. def bhaskara(eq):
  13.     d = delta(eq)
  14.  
  15.     x1 = (-eq['b'] + math.sqrt(d)) / (2 * eq['a'])
  16.     x2 = (-eq['b'] - math.sqrt(d)) / (2 * eq['a'])
  17.  
  18.     return (x1, x2)
  19.  
  20. def gen_pop():
  21.     pop = [(round(random.uniform(-10, 10),2),round(random.uniform(10, 10),2)) for _ in range(SIZE)]
  22.  
  23.     return pop
  24.  
  25. def fitness(z, t, eq):
  26.     fit1 = (eq['a'] * pow(z, 2)) + (z * eq['b']) + eq['c']
  27.     fit2 = (eq['a'] * pow(t, 2)) + (t * eq['b']) + eq['c']
  28.  
  29.     fit1 = abs(fit1)
  30.     fit2 = abs(fit2)
  31.  
  32.     return round((fit1 + fit2)/2, 2)
  33.  
  34. def torneio(pop):
  35.     nova_pop = []
  36.  
  37.     for ind in pop:
  38.         torneio = random.sample(pop, 2)
  39.         melhor_individuo = []
  40.         melhor_fit = 100000
  41.         for i in torneio:
  42.             fit = fitness(ind[0], i[1], EQ)
  43.             if fit < melhor_fit:
  44.                 melhor_fit = fit
  45.                 melhor_individuo = i
  46.         nova_pop.append(melhor_individuo)
  47.  
  48.     return nova_pop
  49.  
  50. def mutation(pop):
  51.     for i in range(len(pop)):
  52.        
  53.         r = random.randint(0, 100)
  54.         if r >= 70:
  55.             a, b = pop[i]
  56.  
  57.             v = random.uniform(-2, 2)
  58.  
  59.             fit1 = fitness(a, a, EQ)
  60.             fit2 = fitness(b, b, EQ)
  61.  
  62.             if fit1 <= 0.5 and fit2 <= 0.5:
  63.                 continue
  64.  
  65.             pos = random.randint(0, 1)
  66.  
  67.             if pos == 0:
  68.                 pop[i] = (a+v, b)
  69.             else:
  70.                 pop[i] = (a, b+v)
  71.  
  72.     return pop
  73.  
  74. if __name__ == '__main__':
  75.     pop = gen_pop()
  76.  
  77.     print("População Inicial:")
  78.     print(pop)
  79.    
  80.     overall_fitness = [fitness(ind[0], ind[1], EQ) for ind in pop]
  81.  
  82.     for _ in range(N_REP):
  83.         pop = torneio(pop)
  84.         pop = mutation(pop)
  85.         overall_fitness = [fitness(ind[0], ind[1], EQ) for ind in pop]
  86.  
  87.     pop = [(round(ind[0], 2), round(ind[1], 2)) for ind in pop] # Arredonda os resultados para 2 casas decimais
  88.  
  89.     print(f"\nPopulação após {N_REP} repetições:")
  90.     print(pop)
  91.  
  92.     print(f"\nSolução ótima: {bhaskara(EQ)}\nMelhor indivíduo encontrado: {pop[0]}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement