AngouriMath
Navigation
Compilation
We will consider ways to improve the performance of computations via compiling functions.
Compilation into a native delegate
Here we will consider a bunch of methods, which all are overloads of one:
Entity expr = "sin(x)";
Func<float, float> mySin = expr.Compile<float, float>("x");
Console.WriteLine(mySin(4.2f));
Output:
-0.87157565
The variable
Entity expr = "sqrt(sin(x) + 3)";
var f = expr.Compile<float, float>("x");
Console.WriteLine(f(4.2f));
Output:
1.458912
The number
Entity expr = "sqrt(sin(x) + 3)";
var f = expr.Compile<int, int>("x");
Console.WriteLine(f(4));
Output:
1
You can also pass multiple parameters, as well as multiple parameters of different types. Example:
Entity expr = "sin(x) + y";
var f = expr.Compile<float, double, float>("x", "y");
Console.WriteLine(f(4.3f, 7.8d));
Output:
6.883834
The supported types are:
using System.Numerics;
Entity expr = "x + y";
var f = expr.Compile<Complex, int, Complex>("x", "y");
Console.WriteLine(f(new(4, 5), 5));
Output:
<9; 5>
You can pass up to 8 type parameters excluding the one for output.
Extensions include the same set of methods, but for string.
If needed to pass more than 8 parameters, or other types than the ones listed, or
custom rules for types, consider declaring your own
CompilationProtocol
Since the way AM compiles an expression is through Linq.Expression, it requires provided rules for constants to be converted into a constant, unary/binary/n-ary nodes to be converted into calls or operators.
That is why AM has class
Its property
...
return typeHolder switch
{
Sumf => Expression.Add(left, right),
Minusf => Expression.Subtract(left, right),
Mulf => Expression.Multiply(left, right),
Divf => Expression.Divide(left, right),
...
Same way it is recommended to define
Now, after you defined your own compilation protocol, you need to pass your delegate and parameters of the final function:
Entity expr = "x + y";
var f = expr.Compile<Func<float, float, float>>(
new(), typeof(float),
new[] { (typeof(float), Var("x")), (typeof(float), Var("y")) }
);
Console.WriteLine(f(4, 5));
Here we use
Compilation into FastExpression
It is highly recommend to compile a given expression the way it is described above.
It does not accept any arguments, as it unconditionally work with
Entity expr = "x + y";
var f = expr.Compile("x", "y");
Console.WriteLine(f.Call(4, 5));
Output:
<9; 0>
It is not as fast and flexible as
Angouri © 2019-2026 · Project's repo · Site's repo · Octicons · Transparency · 5629 pages online