Monday, December 15, 2008

Interactive Function Plotting Using Runtime Compilation of C# Assemblies

Every once in a while I have a need to plot some arbitrary mathematical function to see what it looks like. It happened to me recently when working on my FM Synth project, so I decided to whip up a quick-and-dirty plotting app.

The main issue with creating the app was how to allow for specifying the function(s) to be plotted. Obviously, I did not want to write a custom mathematical function parser. Instead, I leveraged the ability of .NET to create assemblies at runtime using the CodeDomProvider class.

I already had some code to do this that I used to allow runtime evaluation of C# expressions in the console of my city driving game, and I was able to repurpose it with very little effort.

The result is pretty cool. Any number of functions can be specified as arbitrary C# expressions. I dynamically create a class, and add the expressions as methods within it. I also a a special property, 'X', which returns the current X value of the plot. As you can see below, you can call one function from within another and use multiple lines of code.

The start and end values for X are also arbitrary expressions.

The use of CodeDomProvider to generate assemblies at runtime is definitely a very powerful tool that I'm sure I'll find more uses for.


  1. This may be a stupid question but I would really like to know how you did it programmaticaly...

    Here's the situation I'm in:
    I would like to create an application similar to this one.
    The user can give in a function to plot, which then need to be shown on a usercontrol.
    This usercontrol contains a canvas.
    Obviously this has to be done by runtime compilation, and this I understand...
    But I'm stuck at the fact that I don't know how to draw the function exactly.

    My question is basically:
    How did you plot the function by code?
    Because one function can be totally different from an other...

    With regards,
    a Belgian student. :)

  2. That's where the runtime compilation comes in. The function that you type in is compiled into a class with a method that gets passed a value for X and returns a value for Y. Then it is just a simple plot - iterate over the range of X values and plot the resulting Y values.