I've managed to successfully call into SymPy to get this done from C#. SymPy provides a relatively robust simplify function that I've had good success with. Now I'm not entirely sure how to package this nicely yet (not having to install ironpython), or even how hard a direct port of the code might be.
- Install IronPython
- Get SymPy
- Add these resources to your project
- IronPython.dll
- IronPython.Modules.dll
- Microsoft.Dynamic.dll
- Microsoft.Scripting.dll
C# code as follows:
var engine = Python.CreateEngine();
var paths = engine.GetSearchPaths();
paths.Add(@"c:\program files (x86)\ironpython 2.7\lib");
paths.Add(@"c:\Development\sympy");
engine.SetSearchPaths(paths);
// expression to simplify
var expr = "0 + 1 * 1 * (x - 2) / (1 - 2) * (x - 3) / (1 - 3) * (x - 4) / (1 - 4) + 8 * 1 * (x - 1) / (2 - 1) * (x - 3) / (2 - 3) * (x - 4) / (2 - 4) + 27 * 1 * (x - 1) / (3 - 1) * (x - 2) / (3 - 2) * (x - 4) / (3 - 4) + 64 * 1 * (x - 1) / (4 - 1) * (x - 2) / (4 - 2) * (x - 3) / (4 - 3)";
var scope = engine.CreateScope();
var script = engine.CreateScriptSourceFromString(@"
from sympy import *
import clr
from System import String
expr = simplify('" + expr + @"')
result = clr.Convert(expr, String)
");
script.Execute(scope);
// prints "x**3"
Console.WriteLine(scope.GetVariable("result"));