Graph an equation entered by the user in C#

The example Graph an equation y = F(x) in C# shows how to graph a function. The example Evaluate numeric expressions that are entered by the user in C# shows how to compile user-entered equations. This example combines those two techniques to graph a function entered by the user.

The program takes the user-entered equation and uses it to build a C# class that looks like this:

public static class Evaluator
{
    public static double Evaluate(double x)
    {
        return  (1 / x + 1 / (x + 1) - 2 * x * x) / 10;
    }
};

It then compiles this code and gets a MethodInfo object representing the Evaluator class's Evaluate method (as described in the example Evaluate numeric expressions that are entered by the user in C#).

Next the program loops through x values to draw the graph (as done in the example Graph an equation y = F(x) in C# ). It uses the MethodInfo object's Invoke method to call the Evaluate function for the different x values and uses the results to draw the graph.

The only really new thing to notice here is that you only need to compile the function once and then you can invoke it many times. That's important because compiling the function takes a bit of time so recompiling every time you needed to evaluate the function would be relatively time consuming.

See the previous examples and download this example's code to see the details.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Enter the above security code (required)

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.