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.

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

Take a look at this example:

It does a fancier job of expression evaluation and can handle functions such as sin, cos, and sqrt.

2 years on I know this is tough luck but –

How would one create a point on the graph, not picturebox so abit of validation needed, and for that point to show the co-ordinates of the graph.

Or even simpler, how would you hover over the graph and give the real coordinates of the coordinate system made in this, but not the forms.

This program uses a transformation to map world coordinates onto the screen. If you use the

MouseMoveorMouseDownevent handler, the mouse’s position will be in device coordinates, so you need to map it back to world coordinates.Use the

inversetransformation to map the coordinates to world coordinates. You can save that matrix in a class-level variable so you don’t need to recreate it all the time.I may make a follow-up example when I have the time.

Not as simple as I had hoped, but take a look at this example:

Display tooltips on a graph of an equation entered by the user in C#

Pingback: Display tooltips on a graph of an equation entered by the user in C# - C# HelperC# Helper