![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhr5GadgtZw86cRHenPw-y7kOpMOUq8lGolecNKoUXVjfE3-zLZoiAqSLz0tMG-h7gMKn7vlDv3d0V6Rl1LuFIbbs4UsAdSfSL2AUf1eEr4DmGzxC0A4KS9yV7XLYsZlxLFX1Zu1Lt6kY0/s800/Plot1.png)
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.
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgh2xHjQ1upIjrd1rRDoDwSVwAUvrpJ8PYYhS2oHVZLfy_vhP5fxTwXphO_9L4TuG22AKPlyFsoAe61y5g_3hhtXB1Wvo2KzN106VdzuscCmeBS8IKDZ2ZdmiO5Rb0nZvGPHmkiYbSKHGA/s800/Plot2.png)
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.
This may be a stupid question but I would really like to know how you did it programmaticaly...
ReplyDeleteHere'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. :)
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.
ReplyDelete