double Chromosome::create_random_gene(double const& gene_min,
	                                  double const& gene_max,
									  std::mt19937& urng) const
{
	std::uniform_real_distribution<> uniform_distr(gene_min, gene_max);
	return uniform_distr(urng);
}
Esempio n. 2
0
double Particle_source::random_in_range( 
    const double low, const double up, 
    std::default_random_engine &rnd_gen )
{
    std::uniform_real_distribution<double> uniform_distr( low, up );
    return uniform_distr( rnd_gen );
}
int Generation::tournament_selection(std::mt19937& urng) const
{
	std::uniform_int_distribution<int> uniform_distr(0, size-1);
	int n1 = uniform_distr(urng);
	int n2 = uniform_distr(urng);
	if (chromosomes[n1].fitness < chromosomes[n2].fitness) return n1;
	else                                                   return n2;
}
void Generation::mutate_chromosome(Chromosome& chromosome, 
	                               double const& prob_mutation,
								   std::vector<bound> const& param_bounds, 
								   std::mt19937& urng) const
{
	std::uniform_real_distribution<> uniform_distr(0.0, 1.0);
	for (size_t i = 0; i < chromosome.size; ++i) {
		if (uniform_distr(urng) <= prob_mutation) {
			chromosome.genes[i] = chromosome.create_random_gene(param_bounds[i].lower, param_bounds[i].upper, urng);
		}
	}
}
void Generation::crossover_chromosomes(Chromosome& chromosome1, Chromosome& chromosome2, 
	                                   double const& prob_crossover, 
									   std::mt19937& urng) const
{
	std::uniform_real_distribution<> uniform_distr(0.0, 1.0);
	if (uniform_distr(urng) <= prob_crossover) {
		std::vector<double> genes_temp; genes_temp.reserve(chromosome1.size); // store initial genes of the 1st chromosome
		for (size_t i = 0; i < chromosome1.size; ++i) genes_temp.push_back(chromosome1.genes[i]);
		std::uniform_int_distribution<int> uniform_distr2(1, chromosome1.size - 2); 
		int point = uniform_distr2(urng); // choose a random crossover point
		for (int i = 0; i <= point; ++i) {
			chromosome1.genes[i] = chromosome2.genes[i];
			chromosome2.genes[i] = genes_temp[i];
		}
	}
}