Search code examples
classfunctionmethodsfitness

*Passing a Method into a Class


I'm coding a small class that maximizes a given function F and returns the coordinates. For example in maximizing the 1-dimensional fitness function below I currently have:

using System;

public static class Program
{
    public static double F(double x)
    {
        // for example
        return Math.Exp(0.4 * Math.Pow(x - 0.4, 2) - 0.08 * Math.Pow(x, 4));
    }

    static void Main(string[] args)
    {

    Metaheutistic Solve = new Metaheutistic;

    Solve.Maximize(Mu, Lambda, Theta);

    }
}

The method "Maximize" in the class Metaheutistic contains the algorithm that does all the work. My problem is this algorithm is in a class that does not know what the fitness function looks like.

I'm new to C# and if I've gone on a bender here I'm open to doing it all over again to get it right. I do however need to keep the Solver class separate from the fitness function.

Many thanks. *I'm not sure "Passing" is the correct term I'm looking for


Solution

  • You can indeed pass methods into functions using a delegate, for example:

    public delegate double FitnessDelegate(double x);
    

    declares a delegate to a function which takes a double parameter and returns a double. You can then create a reference to the real function, and pass this to the Solve method to be called.

    public static class Program
    {
        public static double F(double x)
        {
            // for example
            return Math.Exp(0.4 * Math.Pow(x - 0.4, 2) - 0.08 * Math.Pow(x, 4));
        }
    
        static void Main(string[] args)
        {
        FitnessDelegate fitness = new FitnessDelegate(F);
        Metaheutistic Solve = new Metaheutistic;
    
        Solve.Maximize(fitness);
    
        }
    }
    

    within the Solve method you may call this delegate as you would a method and it will in fact be executing the actual method:

    class Metaheutistic 
    {
      public void Maximise(FitnessDelegate fitness)
      {
        double result = fitness(1.23);
      }
    }