Skip to content

Advanced Usage

Marcus Ackre Medina edited this page Sep 13, 2026 · 1 revision

Advanced Usage

Beyond building, evaluating, and printing expressions (see Getting Started and API Overview), a few features are worth knowing about.

Substitute — swap a variable for a value or another expression

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 = 10

Both overloads return a new IAlgebraExpression — the original is untouched, so you can build one expression and substitute into it repeatedly for different inputs.

Simplify — constant folding and identity rules, not full CAS simplification

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)) becomes Constant(5)).
  • Additive identity: x + 0 and 0 + x simplify to x.
  • Multiplicative identity: x * 1 and 1 * x simplify to x.
  • Multiplicative zero: x * 0 and 0 * x simplify to 0.

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 + 5

Custom variables and function composition

Algebra.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)); // ~1

Parsing and evaluating in one pass over a range

Combine 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);
}

What this library doesn't do

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.