Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- import numpy as np
- import matplotlib.pyplot as plt
- HMCR = 0.7 # вероятность выбора из гармоник в памяти
- PAR = 0.5 # вероятность модификации
- BW = 0.04
- counter = 0
- harmony = [[-37.5, 23],
- [-41, -36],
- [47, -31],
- [49, 11],
- [17, 25]]
- n = int(input("Iteration number = "))
- dimensions = [[-100, 100],
- [-100, 100]]
- res_plot = []
- def fitness_function(v):
- return v[0] * v[0] + v[1] * v[1]
- while counter < n:
- worst_i = 0 # индекс максимального элемента в старой гармонии (для редактирования элемента списка)
- best_i = 0 # индекс минимального элемента в новой гармонии (для считывания конкретного элемента в списке)
- # т.к. в противном случае будет создаваться ссылка на существующий список
- i1 = np.random.randint(0, len(harmony), size=1)[0]
- X1 = [None] * len(harmony[i1])
- X1_flags = [False] * len(X1)
- for j in range(len(harmony[i1])):
- if random.random() < HMCR:
- X1[j] = harmony[i1][j]
- X1_flags[j] = True
- else:
- U1 = random.random()
- X1[j] = dimensions[j][0] + U1 * (dimensions[j][1] - dimensions[j][0])
- for j in range(len(X1)):
- if X1_flags[j] and random.random() < PAR:
- N1 = np.random.normal()
- u_sign = random.choice([-1, 1])
- X1[j] = X1[j] + u_sign * BW * N1
- # нахождение худшего элемента в старой гармонии
- worst_result = -65000
- for i in range(len(harmony)):
- res = fitness_function(harmony[i])
- if res > worst_result:
- worst_result = res
- worst_i = i
- if fitness_function(X1) < worst_result:
- harmony[worst_i] = X1
- counter += 1
- min_i = -1
- min_result = 65000
- for i in range(len(harmony)):
- res = fitness_function(harmony[i])
- if res < min_result:
- min_result = res
- min_i = i
- print(harmony[min_i])
- res_plot.append(harmony[min_i])
- print(min_result)
- plt.plot(res_plot)
- plt.ylabel('Best results:')
- plt.savefig("harmony.png")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement