Parse math strings into Delegates for real and complex numbers.
There are only two methods and two number spaces to choose from, but more to this later. Let's run the most basic form.
var del = MathExpressionCompiler.CreateDelegate<double>("length + 3 * height", out string[] variableNameList);
Console.WriteLine($"[{string.Join(", ", variableNameList)}]");
//> [length, height]
Console.WriteLine(del.DynamicInvoke(4,7));
//> 25
If you want to change number space to complex
var del = MathExpressionCompiler.CreateDelegate<Complex>("length + 3 * height", out string[] variableNameList);
Console.WriteLine($"[{string.Join(", ", variableNameList)}]");
//> [length, height]
Console.WriteLine(del.DynamicInvoke(new Complex(4,2),new Complex(5,7)));
//> <19; 23>
When using the complex numberspace, you can also create a delegate that takes doubles and just sets the imaginry part to 0.
var del = MathExpressionCompiler.CreateDelegateWithDoubleParameters<Complex>("length + 3 * height", out string[] variableNameList);
Console.WriteLine(del.DynamicInvoke(4,7));
//> <25; 0>
Since i
will be parsed as the complex unit you can still implement complex functions this way.
var del = MathExpressionCompiler.CreateDelegateWithDoubleParameters<Complex>("a + b * i", out string[] variableNameList);
Console.WriteLine(del.DynamicInvoke(4,7));
//> <4; 7>
Another usecase for this is entering a value using polar coordinates
var del = MathExpressionCompiler.CreateDelegateWithDoubleParameters<Complex>("polar(a,b)", out string[] variableNameList);
Console.WriteLine(del.DynamicInvoke(4,7));
//> <3,0156090173732184; 2,6279463948751562>
- All strings get transformed to lowercase.
- Use
*
to connect numbers and variables. For now sloppy notation will not get fixed. - To prevent scoping confusion all methods like
sqrt
,sin
,cos
... need to be followed by(<term>)
. - Methods taking multiple parameters like
sum
have their parameters seperated by,
:sum(x,1,4,x/2)
. - Spaces can be used to make you equations easier to read.
In the folowing table all parameters can be any term except the ones being shown as VAR
. They have to be a variable name.
Operation | Syntax | Description |
---|---|---|
Addition | x + y |
Add x and y |
Subtraction | x - y |
Subtract y from x |
Multiplication | x * y |
Multiply x and y |
Division | x / y |
Divide x by y |
Power | x ^ y |
x to the power of y |
Sinus | sin(x) |
Sinus of x |
Cosinus | cos(x) |
Cosinus of x |
Tangent | tan(x) |
Tangent of x |
Square Root | sqrt(x) |
Square root of x |
Polar | polar(x,y) |
Create Complex from polar using x.Real and y.Real |
Sum | sum(VAR,a,b,c) |
Add together each iteration of c . Start Var = a and end VAR = b |