#交叉 defcrossover(parent,population):#其实,population 与parent是一个东西 if np.random.rand()<CROSS_RATE: i_=np.random.randint(0,POP_SIZE,size=1)#选择母本 cross_points=np.random.randint(0,2,size=DNA_SIZE).astype(np.bool) parent[cross_points]=population[i_,cross_points] return parent#此时的parent已经是child了
#变异 defmutate(child): for point inrange(DNA_SIZE): if np.random.rand()<MUTATION_RATE: child[point]=1if child[point]==0else0 return child
if __name__ == '__main__': plt.ion() # something about plotting x = np.linspace(*X_BOUND, 200) plt.plot(x, F(x)) population=np.random.randint(2,size=(POP_SIZE,DNA_SIZE)) for _ inrange(N_GENERATIONS): F_values=F(translateDNA(population))