index > Visual C# General > (INTEGRATE) Convert a string to a Function

(INTEGRATE) Convert a string to a Function

I am trying to integrate a math function 'func' which will be entered(typed) by the user, but I cannot figure out how to convert the string to a function which would be called by the integtal function.

double integral(double xLeft, double xRight, double func(double), int nDivs)
{
int i;
double area = 0.0;

double deltaX = (xRight - xLeft)/nDivs;

double midpointX;

midpointX = xLeft + deltaX/2.0;

for (i = 0; i < nDivs; i++)
{
area += func(midpointX) * deltaX;

midpointX += deltaX;



}

return area;
}

Thanks for any help




Electronics and Computer Hobbyist
arpan_1234
do u mean, how to convert string to double?
Rahul Saxena
Hi. what you need is something similar to callback functions? That can be done using delegates.

delegate double Func(double str);

public double realFunc(double val)
{
...
}

double integral(double xLeft, double xRight, Func func, int nDivs)
{
...
area += func(midpointX) * deltaX;
...
}

void Test()
{
integral(..., ..., new Func(realFunc), ...);
}

Bye.
daniel testa

No, he means he's got a string like "x+1", "x*x" or "sin(x)" and he wants to programmatically evaluate this for any given x.

I don't know a good way to do this. For simple maths syntax, this may be possible using Microsoft.CSharp.CSharpCodeProvider to parse the expression and generate a function.

Rup

Thanks ,

Yes I wanted to enter a string like : "x+1", "x*x" or "sin(x)".

I am trying the hint by "Rup" , but i want some more help regarding this.




Electronics and Computer Hobbyist
arpan_1234

I can't help you with that, sorry, I've never used that class myself -

but an alternative is to write an expression parser and calculator yourself. There's a few on Google: one here in VB

http://www.codeproject.com/vb/net/math_expression_evaluator.asp

which probably won't be too hard to integrate with your C# code (or port over to C#) or, if you're a bit more adventerous, there's a number on sourceforge.net written in Java or C you could try instead. (I searched for "expression".) Given you're going to be computing the function for very many values to approximate the integral you'd want an approach that parsed the text expression into a tree of operations or similar so that you could easily recompute it without having to parse the string each time.

Rup

Fallback to XPath:

class Program
{
static void Main(string[] args)
{
XPathExpression expr = XPathExpression.Compile("2+4+6");
XmlDocument xmlDoc = new XmlDocument();
XPathNavigator xPathNavigator = xmlDoc.CreateNavigator();
Console.WriteLine(xPathNavigator.Evaluate(expr));
}
}

xPathNavigator.Evaluate will give you the result of the string. You can change the variables either via a stringreplace before calling Compile or if you want to be more sophisticated you can implement your own xpath resolver that will get the values from somewhere else during execution.

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=365098&SiteID=1

John.Doe

Working with in memory compilation is also a nice idea, e.g.:

class Program
{
static Type PrepareCalcClass(string calcString)
{
// namespace CalcNS
CodeNamespace codeNamespace = new CodeNamespace("CalcNamespace");
// class Calc
CodeTypeDeclaration calcType = new CodeTypeDeclaration("CalcClass");
codeNamespace.Types.Add(calcType);
// public double Calc(double x) { return <calcString>; }
CodeMemberMethod method = new CodeMemberMethod();
method.Attributes =
MemberAttributes.Public | MemberAttributes.Static;
method.Name =
"Calc";
method.Parameters.Add(
new CodeParameterDeclarationExpression(typeof(double), "x"));
method.ReturnType =
new CodeTypeReference(typeof(double));
method.Statements.Add(
new CodeMethodReturnStatement(new CodeSnippetExpression(calcString)));
calcType.Members.Add(method);

// compile
CodeCompileUnit compileUnit = new CodeCompileUnit();
compileUnit.Namespaces.Add(codeNamespace);
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory =
true;
CompilerResults compilerResults = provider.CompileAssemblyFromDom(parameters, compileUnit);

// errors?
if ((compilerResults.Errors != null) &&
(compilerResults.Errors.Count > 0))
{
string errors = String.Empty;
foreach (string error in compilerResults.Errors)
errors += error +
"\n";
throw new Exception("compilation failed\n" + errors);
}
Type type = compilerResults.CompiledAssembly.GetType("CalcNamespace.CalcClass");
return type;
}

static void Main(string[] args)
{
Type type = PrepareCalcClass("x*x");
MethodInfo calcMethodInfo = type.GetMethod("Calc", BindingFlags.Static|BindingFlags.Public);
for (int x = 0; x < 10; x++)
{
double result = (double)calcMethodInfo.Invoke(null, new object[] { (double)x });
Console.WriteLine(result);
}
}
}

Just modify it to your needs...

John.Doe

Thanks John for the time you spent around my problem. I am trying your method, I will try to reply as soon as possible.

I cannot be online tomorrow, because of some problem..

Regards...




Electronics and Computer Hobbyist
arpan_1234

Yes, i wanted to evaluate "x+1", "x*x" or "sin(x)" etc programmatically as pointed by "Rup"

I tried hint of using the method using -

Microsoft.CSharp.CSharpCodeProvider

but still cannot do the required, can anyone give some around this problem ..

Thanks....




Electronics and Computer Hobbyist
arpan_1234
What exactly does not work? That was a full example of how to compile a string to a class with a function and how to call it...
John.Doe

I got that program done and running

Thanks...




Electronics and Computer Hobbyist
arpan_1234
reply 12

You can use google to search for other answers

 

More Articles

• Big problem on setup??aybe it's a bug?
• How I can send SMS(Short Message Service)?
• obteining a printer status using WMI in windows 2000
• Advice wanted: C# version of Java applet wanted
• Simple 'passing variables between forms' issue...  I hope.
• Interope
• I Need A Smple For Receiving SMS In Side My Own Programm (PPC 200...
• Binding DataTable to DataGridView column
• The type <sometype> exists in both <frameworkdirectory&g...
• How can I get the length of a remote file??
Bookmark and Share
Welcome to Bokebb   New Update  
 

New Articles

• POP Connection
• attempting to use an array across a class
• How to limit number of child form in par
• Outlook Hyperlink
• FileInfo.CreationTime resolution
• How to Display ASP.NET Template Contents
• Copy a table From Sql Server 2000 to ms
• character literal for escape
• why i=i++ is undefined and have very str
• Set Localizable for all solution
• drawing something to the form---
• Why does this code stop responding in a
• How to display MS word document to the p
• can i write to: global::Proj.Properties.
• Dataset for programmaticly generated data

Hot Articles

• How to add a directory structure to a pr
• User Control containing HTML controls
• information path is required
• can someone convert this snipet of VB to
• CRectTrack
• WMP custom skin
• How to update DB from dataGridView using
• where is it? Microsoft.Office.Interop.Ex
• UserControl Close, Exit, Terminate, Etc.
• DLL Files
• Exception Handling Techniques for ASP.NE
• Item Template Problem
• Execute Specified Form
• help with structs and arrays
• Create an event for the close button on

Recommend Articles

• Communicating with my USB MIDI Keyboard..
• MSDN Library for VS.NET 2003 download
• Find width of character of a font
• Disable Screen Saver
• Updating references
• MDI child is removed from window list wh
• MCE full screen question
• Stop DELETE action
• ASP usercontrol with C#
• How to Create CHM File Using C#?
• Independent slide
• Errors while viewing usercontrol's desig
• FindControl() Windows Forms Equivalent??
• Database Connection String
• file down loader heeeelllp!!!!!