Dynamically generate a function expression (C #)

Source: Internet
Author: User
I mentioned in an article "draw a C # program of function graphics and a pathological function:

C # Of the function Image # ProgramOne serious drawback is that function expressions are directly written in the source program and cannot be input interactively like SCILAB and Matlab. I don't know if the system. reflection. emit. ilgenerator class can dynamically generate the function expression entered by the user?

"Space/IV" points out in the comment below:

To dynamically generate the function expression entered by the user, it may be helpful to see the following post:
Http://community.csdn.net/Expert/topic/4169/4169185.xml

After research, I wrote a class expression that dynamically generates the function expression you entered. The expression uses the C # syntax and can contain an independent variable (X ), the Independent Variables and values are of the "double" type. The following is the running result of the test program:

C> expressiontest
Usage: expressiontest expression [parameters...]

 

C> expressiontest math. Pi * Math. E 0
F (x): Math. Pi * Math. e
F (0) = 8.53973422267357

C> expressiontest math. Pow (2, x) 0 10 49 50 1024-1-1024
F (x): Math. Pow (2, X)
F (0) = 1
F (10) = 1024
F (49) = 562949953421312
F (50) = 1.12589990682132e + 15
F (1024) = positive infinity
F (-1) = 0.5
F (-1024) = 5.562684646268e-309

C> expressiontest "double U = math. pi-X; double Pi2 = math. pI * Math. pi; return 3 * x + math. log (u * u)/Pi2/Pi2 + 1; "3.13 3.14 3.15 3.16
F (x): double U = math. pi-X; double Pi2 = math. pI * Math. pi; return 3 * x + math. log (u * u)/Pi2/Pi2 + 1;
F (3.13) = 30.2991811562164
F (3.14) = 30.44652582187
F (3.15) = 30.6693849404716
F (3.16) = 30.8747746902426
F (3.1416) = 30.3662371931734

The last example is the calculation result of the following functions:

In fact, this pathological function is called the C value. Algorithm(Version 2) as mentioned in chapter 3 "inner plug-in and external push methods:

---------------------------------------------------------------------------
It is easy to construct some pathological functions to make the internal Insertion Method fail. For example, consider the Function
F (x) = 3 * X2 + π-4 * ln [(π-x) 2] + 1
It is defined in addition to X = π, but not in X = π. In other cases, values are positive and negative. This function will certainly get an incorrect solution at x = 3.13 In any interpolation method based on values x = 3.14, 3.15, 3.16, and 3.1416, although the curves drawn from these five points are indeed quite smooth! (Use a calculator .)
---------------------------------------------------------------------------

It can be seen that, in any interpolation method based on values x = 3.13, 3.14, 3.15, and 3.16, the solution obtained at x = 3.1416 must be between 30.44652582187 and 30.6693849404716, however, the actual solution should be 30.3662371931734, so the author asserted that there would certainly be a wrong solution.
The following is the source program: // Expressiontest. CS-a test program that dynamically generates a mathematical expression and calculates its value
// Compilation Method: CSC expressiontest. CS expression. CS

Using System;
Using Skyiv. util;

Namespace Skyiv. Test
{
Class Expressiontest
{
Static   Void Main ( String [] ARGs)
{
Try
{
If (ARGs. Length >   0 )
{
Console. writeline ( " F (x): {0} " , ArgS [ 0 ]);
Expression expression =   New Expression (ARGs [ 0 ]);
For ( Int I =   1 ; I < Args. length; I ++ )
{
DoubleX= Double. Parse (ARGs [I]);
Console. writeline ("F ({0}) = {1}", X, expression. Compute (x ));
}
}
Else Console. writeline ( " Usage: expressiontest expression [parameters] " );
}
Catch (Exception ex)
{
Console. writeline ("Error:" +Ex. Message );
}
}
}
}
// Expression. CS-dynamically generate a mathematical expression and calculate its value
// The expression uses the C # syntax and can contain an independent variable (X ).
// The Independent Variables and values of an expression are of the (double) type.
// Example:
// Expression expression = new expression ("math. Sin (x )");
// Console. writeline (expression. Compute (math. PI/2 ));
// Expression = new expression ("double U = math. Pi-X;" +
// "Double Pi2 = math. Pi * Math. Pi;" +
// "Return 3 * x + math. Log (u * u)/Pi2/Pi2 + 1 ;");
// Console. writeline (expression. Compute (0 ));

Using System;
Using System. codedom. compiler;
Using Microsoft. CSHARP;
Using System. reflection;
Using System. text;

Namespace Skyiv. util
{
Sealed   Class Expression
{
Object Instance;
Methodinfo method;

Public Expression ( String Expression)
{
If (Expression. indexof ( " Return " ) <   0 ) Expression =   " Return "   + Expression +   " ; " ;
String Classname =   " Expression " ;
String Methodname =   " Compute " ;
Compilerparameters P =   New Compilerparameters ();
P. generateinmemory =   True ;
Compilerresults cr =   New Csharpcodeprovider (). compileassemblyfromsource (p, String .
Format ( " Using system; sealed class {0 }{{ public double {1} (Double X) {{{ 2 }}}}} " ,
Classname, methodname, expression ));
If (Cr. errors. Count >   0 )
{
String MSG =   " Expression (\ "" + Expression + " \ " ): \ N " ;
Foreach (Compilererror err In Cr. Errors) msg + = Err. tostring () +   " \ N " ;
Throw   New Exception (MSG );
}
Instance = Cr. compiledassembly. createinstance (classname );
Method = Instance. GetType (). getmethod (methodname );
}

Public   Double Compute ( Double X)
{
Return(Double) Method. Invoke (instance,New Object[]{X});
}
}
}

To the csdn Forum,Lovecherry! ^_^)"Thanks, my program developed on the basis of his program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.