Skip to content

Instantly share code, notes, and snippets.

@yetanotherchris
Created February 19, 2013 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yetanotherchris/4984735 to your computer and use it in GitHub Desktop.
Save yetanotherchris/4984735 to your computer and use it in GitHub Desktop.
GA1: Example usage
public static void Main()
{
// Crossover = 80%
// Mutation = 5%
// Population size = 100
// Generations = 2000
// Genome size = 2
GA ga = new GA(0.8, 0.05, 100, 2000, 2);
ga.FitnessFunction = FitnessFunction;
ga.Elitism = true;
ga.Go();
double[] values;
double fitness;
ga.GetBest(out values, out fitness);
System.Console.WriteLine("Best ({0}):", fitness);
for (int i = 0; i < values.Length; i++)
System.Console.WriteLine("{0} ", values[i]);
ga.GetWorst(out values, out fitness);
System.Console.WriteLine("\nWorst ({0}):", fitness);
for (int i = 0; i < values.Length; i++)
System.Console.WriteLine("{0} ", values[i]);
Console.Read();
}
// optimal solution for this is (0.5,0.5)
public static double FitnessFunction(double[] values)
{
if (values.GetLength(0) != 2)
throw new ArgumentOutOfRangeException("should only have 2 args");
double x = values[0];
double y = values[1];
double n = 9; // should be an int, but I don't want to waste time casting.
double f1 = Math.Pow(15 * x * y * (1 - x) * (1 - y) * Math.Sin(n * Math.PI * x) * Math.Sin(n * Math.PI * y), 2);
return f1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment