Graph equations entered by the user in C#


This example draws a graph of an equation entered by the user by combining techniques from the following two posts:

This example uses techniques from first post to compile the equation entered by the user. It takes the text entered by the user and builds a C# class similar to the following.

using System;

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

The program then compiles this code and gets a MethodInfo object representing the Evaluator class’s Evaluate method.

Next the program loops through X values to draw the graph as done in the second post listed above. 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 to draw the graph. 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.

Note that you must capitalize Math library methods correctly to make a graph. For example, to use the sine function you must spell if Math.Sin as shown in the picture at the top of the post. Also note that the looping variable x must be in lower case within the graph equation.

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

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in algorithms, drawing, graphics, mathematics, reflection and tagged , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Graph equations entered by the user in C#

  1. H. Tabasi says:

    Hello Mr. Rod Stephens
    thank u because of your nice example!
    I learnd much by u and this example!
    but i can’t compile a mathematical equation like this : “sin(x)”
    I don’t know how should i change the code to slove my problem!
    whould you please help me?
    thank you

Leave a Reply

Your email address will not be published. Required fields are marked *