Esempio n. 1
0
        private double computeFitness(Ind individual)
        {
            // -(Pow(x)) + 7x
            var fitness = -(Math.Pow(individual.value(), 2)) + (7 * individual.value());

            return(fitness);
        }
Esempio n. 2
0
        /* Roulette selection */
        private Func <Tuple <Ind, Ind> > selectTwoParents(Ind[] population, double[] fitnesses)
        {
            // Normalize the values
            var lowestFitness  = fitnesses.OrderBy(x => x).First();
            var highestFitness = fitnesses.OrderBy(x => x).Last();

            double[] normalizedFitnesses = new double[fitnesses.Length];

            // All values are between 0-1
            for (var i = 0; i < fitnesses.Length; i++)
            {
                normalizedFitnesses[i] = (fitnesses[i] - lowestFitness) / (highestFitness - lowestFitness);
            }

            var cumProbability   = 0.0;
            var totalProbability = normalizedFitnesses.Sum();

            var avgNormalizedFitnesses = Enumerable.Range(0, populationSize).Select(i => normalizedFitnesses[i] / totalProbability).ToArray();

            Ind parent1 = new Ind();
            Ind parent2 = new Ind();

            for (int i = 0; i < populationSize; i++)
            {
                cumProbability += normalizedFitnesses[i];
                if (cumProbability >= r.NextDouble())
                {
                    if (parent1.value() == 0)
                    {
                        parent1 = population[i];
                    }
                    else
                    {
                        parent2 = population[i];
                        break;
                    }
                }
            }

            return(() => { return new Tuple <Ind, Ind>(parent1, parent2); });
        }