I’m trying to write differential equation solver and i need to allow user to input them by textbox. Problem is that solving method changes when equation contains only x or its something like x+y. Ifound great code on http://www.codeproject.com/KB/recipes/matheval.aspx but i have trouble on extending it into 2 methods
using System;
using System.Collections;
using System.Reflection;
namespace RKF45{
public class MathExpressionParser
{
public object myobj = null;
public ArrayList errorMessages;
public MathExpressionParser()
{
errorMessages = new ArrayList();
}
public bool init(string expr)
{
Microsoft.CSharp.CSharpCodeProvider cp = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.CompilerParameters cpar = new System.CodeDom.Compiler.CompilerParameters();
cpar.GenerateInMemory = true;
cpar.GenerateExecutable = false;
string src;
cpar.ReferencedAssemblies.Add("system.dll");
src = "using System;" +
"class myclass " +
"{ " +
"public myclass(){} " +
"public static double eval(double x) " +
"{ " +
"return " + expr + "; " +
"} " +
"public static double eval2(double x,double y) " +
"{ " +
"return " + expr + "; " +
"} " +
"} ";
System.CodeDom.Compiler.CompilerResults cr = cp.CompileAssemblyFromSource(cpar, src);
foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
errorMessages.Add(ce.ErrorText);
if (cr.Errors.Count == 0 && cr.CompiledAssembly != null)
{
Type ObjType = cr.CompiledAssembly.GetType("myclass");
try
{
if (ObjType != null)
{
myobj = Activator.CreateInstance(ObjType);
}
}
catch (Exception ex)
{
errorMessages.Add(ex.Message);
}
return true;
}
else
return false;
}
public double eval(double x)
{
double val = 0.0;
Object[] myParams = new Object[1] { x };
if (myobj != null)
{
System.Reflection.MethodInfo evalMethod = myobj.GetType().GetMethod("eval");
val = (double)evalMethod.Invoke(myobj, myParams);
}
return val;
}
public double eval2(double x, double y)
{
double val = 0.0;
Object[] myParams = new Object[2] { x, y };
if (myobj != null)
{
System.Reflection.MethodInfo evalMethod = myobj.GetType().GetMethod("eval2");
val = (double)evalMethod.Invoke(myobj, myParams);
}
return val;
}
}
}
Any ideas why eval2 method is not working correclty when i give expression like x+y ? eval is working fine but i need 2 of them to solve different equations inputted in textbox.
You can’t use an expression containing two different variables (like “x” and “y”) both in
eval(double x)andeval(double x, double y)method: the first one won’t compile (since the second variable is not defined there), whereas using expressions containing only single variable (like “x”) compiles in both cases. This explains why you can’t invokeeval2()in case of two variables.