Skip to content

Equation Solver

Marcus Ackre Medina edited this page Jul 20, 2026 · 2 revisions

Equation Solver

Note: as of v0.3.2 there is no EquationSolver class or Solvers namespace shipped in this package — the closed-form/numerical solver API previously described on this page does not exist in the current source. Differentiate() doesn't exist either, so Newton-Raphson isn't available out of the box. This page has been rewritten to show what's actually possible today with Algebra, AlgebraParser and .Evaluate().

Linear — ax + b = 0

Solved directly, no library call needed:

double a = 3, b = -9;
double x = -b / a;  // x = 3

Quadratic — ax² + bx + c = 0

Build the expression, then apply the quadratic formula and verify with .Evaluate():

using MarcusMedina.Maths.Algebra.Builders;
using MarcusMedina.Maths.Algebra.Extensions;
using MarcusMedina.Maths.Algebra.Evaluators;

double a = 1, b = -5, c = 6;

var equation = Algebra.X.Square().Multiply(a)
    .Add(Algebra.X.Multiply(b))
    .Add(c);

double discriminant = (b * b) - (4 * a * c);
double root1 = (-b + Math.Sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.Sqrt(discriminant)) / (2 * a);

Console.WriteLine(equation.Evaluate("x", root1));  // ~0 — verifies the root
Console.WriteLine(equation.Evaluate("x", root2));  // ~0 — verifies the root

This mirrors the UseCase1.EquationSolver sample shipped in the repository.

Bisection (numerical, hand-rolled)

Nothing stops you writing a bisection loop yourself against an AlgebraExpression:

using MarcusMedina.Maths.Algebra.Parsers;
using MarcusMedina.Maths.Algebra.Evaluators;

var f = AlgebraParser.Parse("cos(x) - x");

double low = 0, high = 1, tolerance = 1e-10;
double mid = 0;

while (high - low > tolerance)
{
    mid = (low + high) / 2;
    double fMid = f.Evaluate("x", mid);
    double fLow = f.Evaluate("x", low);

    if (Math.Sign(fMid) == Math.Sign(fLow))
    {
        low = mid;
    }
    else
    {
        high = mid;
    }
}

Console.WriteLine(mid);  // ≈ 0.7391

Requires f(low) and f(high) to have opposite signs.

Scanning a range for roots

.EvaluateRange() is useful for spotting where a function crosses zero before refining with bisection:

var f = AlgebraParser.Parse("x^3 - 2");
var samples = f.EvaluateRange("x", start: 0, end: 2, steps: 20);
// inspect samples for a sign change, then bisect around it

Newton-Raphson

Not currently available — this package has no symbolic differentiation, so there's no f'(x) to feed a Newton-Raphson step without hand-writing the derivative yourself. If you need it, differentiate f by hand and evaluate both f and f' with .Evaluate() inside your own loop.

Clone this wiki locally