Im playing around with a genetic algorithm for solving eqvations. So I've found this lib called NCAL which seems to be a nice way to go.
So I've tried to generate som random strings that will become NCALC Expressions like this:
private Expression getRandomExpression(int i)
{
string expression = ""; ;
double nr = random.NextDouble() * random.Next(100);
int sign = 1;
if (random.Next(2) > 0)
{
sign = -1;
}
Console.WriteLine("sign: " + sign + " i: " + i);
switch (i)
{
case 1:
expression = (sign.ToString() + "*" + nr.ToString() + "x");
break;
case 2:
expression = (sign.ToString() + nr.ToString() + "/x");
break;
case 3:
expression = (sign.ToString() + "x/" + nr.ToString());
break;
case 4:
expression = (sign.ToString() + "Pow(x," + nr.ToString()+")");
break;
default:
expression = (sign.ToString() + "*" + nr.ToString());
break;
}
return new Expression(expression);
}
And then I want to loop over these elements and check the sum against my goalfunction, like this:
public double calculateFitness(double[] goalFunction)
{
double fitness = 0.0;
for (int i = 1; i < goalFunction.Length; i++)
{
foreach (var element in genome)
{
try
{
element.Parameters["x"] = i;
var value = (double)element.Evaluate();
fitness += Math.Abs(goalFunction.ElementAt(i) - value);
}catch(Exception ex)
{
throw ex;
}
}
}
return fitness;
}
Seems easy but I keep getting this exception saying "line 1:1 missing EOF at 'x'". Any suggestions on how to solve this? Or easier ways to go. :) I want to be able to find a equation representing the goalfunction.
br