I am trying to implement an infrastructure in C# that would allow me to make arbitrary mathematical expressions. For example, I want to be able to take an expression like
asin(sqrt(z - sin(x+y)^2))
and turn it into an object that will allow me to evaluate it in terms of x,y, and z, get derivatives, and possibly do some kind of symbolic algebra on it. What are people's thoughts on a good model for this in C#?
I have my own take, which I am afraid is heading off into architecture astronautics, so I want to make sure that is not the case.
Basically, the functions like sin, +, sqrt, etc. have classes based off a base class:
Function
Function<TOut> : Function
TOut Value
Function<Tin, TOut> : Function
TOut Evaluate(TIn value)
Function Derivative
Function<TOut, TIn> INverse
Function<TInA, TInB, TOut> : Function
TOut Evaluate(TInA valueA, TInB valueB)
Function PartialDerivativeA
Function PartialDerivativeB
So far, so simple. The trick is how to compose the functions. Here I believe I want something like a currying approach so that I can evaluate the function for a single parameter, and have the other ones remain. So I am thinking of having a factory class like this:
Function<TInA, TInB, TOut> ->
Function<TInA, Function<TInB, TOut>>
(Function<TInA, TInB, TOut>, Function<TInX, TInA>, null) ->
Function<TInX, Function<TInB, TOut>>
(Function<TInA, TInB, TOut>, Function<TInA>, Function<TInX, TInY, TInB>) ->
Function<TInX, Function<TInY, TInB>>
and so on. My main concerns are that the generic types might make the system unusable (if the user is required to know the full generic types just to evaluate), and that I might not be able to construct all of the generic types from the input arguments.
Thanks for your input!
Note that it is possible to use the C# compiler to evaluate expressions.
Evaluating Mathematical Expressions by Compiling C# Code at Runtime http://www.codeproject.com/KB/recipes/matheval.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With