Repository navigation
Advanced Usage
Beyond building, evaluating, and printing expressions (see Getting Started and API Overview), a few features are worth knowing about.
using MarcusMedina.Maths.Algebra.Builders;
using MarcusMedina.Maths.Algebra.Extensions;
var expr = Algebra.X.Square().Add(1); // x^2 + 1
var withNumber = expr.Substitute("x", 3.0); // (3)^2 + 1, still an expression
Console.WriteLine(withNumber.Evaluate()); // 10
var composed = expr.Substitute("x", Algebra.Y.Add(1)); // (y + 1)^2 + 1
Console.WriteLine(composed.Evaluate("y", 2)); // (2+1)^2 + 1 = 10Both overloads return a new IAlgebraExpression — the original is untouched, so you can build one expression and substitute into it repeatedly for different inputs.
Simplify() recursively simplifies both sides of an expression, then applies a small set of rules:
-
Constant folding: if both sides of a binary operation are constants, it evaluates them immediately (
Constant(2).Add(Constant(3))becomesConstant(5)). -
Additive identity:
x + 0and0 + xsimplify tox. -
Multiplicative identity:
x * 1and1 * xsimplify tox. -
Multiplicative zero:
x * 0and0 * xsimplify to0.
It does not do general algebraic simplification — no combining like terms across a larger tree, no factoring, no trig identities. Treat it as a cheap cleanup pass, not a computer algebra system.
var expr = Algebra.X.Multiply(1).Add(0).Add(Algebra.Constant(2).Add(3));
Console.WriteLine(expr.Simplify()); // x + 5Algebra.Var("theta") (or the equivalent Algebra.Variable(...)) creates a named variable beyond the built-in X/Y/Z, and every math-function extension (.Sin(), .Sqrt(), .Log(), ...) composes normally with it:
var theta = Algebra.Var("theta");
var expr = theta.Sin().Power(2).Add(theta.Cos().Power(2)); // sin(theta)^2 + cos(theta)^2
Console.WriteLine(expr.Evaluate("theta", 1.2)); // ~1Combine AlgebraParser.Parse with .EvaluateRange(...) to sample a function without writing a loop yourself — useful for plotting or scanning for sign changes (see Equation Solver for using this to bracket a root before bisecting).
using MarcusMedina.Maths.Algebra.Parsers;
using MarcusMedina.Maths.Algebra.Evaluators;
var f = AlgebraParser.Parse("x^3 - 2*x - 5");
foreach (var y in f.EvaluateRange("x", start: 0, end: 3, steps: 30))
{
Console.WriteLine(y);
}As of the current source there is no symbolic differentiation (Differentiate) and no EquationSolver/Solvers namespace — see Equation Solver for how to work around both with .Evaluate(), .EvaluateRange(), and a hand-rolled numerical method.