Root Finding Demo — Solving Equations
The calx root-finding module handles everything from 1D nonlinear equations to finding all roots of a polynomial in a unified manner. This page presents three demos covering representative use cases.
Demo 1: Finding sqrt(2) with Brent's Method
We find the positive root of $f(x) = x^2 - 2$ using Brent's method. Brent's method combines the reliability of bisection with the speed of the secant method, making it one of the best practical algorithms.
Demo 2: Verifying the Factorization of a Cubic
We find all roots of $p(x) = x^3 - 6x^2 + 11x - 6 = (x-1)(x-2)(x-3)$ and numerically verify that the factorization is correct. For degree up to 4, the Cardano/Ferrari closed-form formulas are used.
findAllRoots uses closed-form solutions for degree 1 through 4, yielding near-exact results without iteration.
All roots are returned as Complex<T>, but in this example the imaginary parts are all 0 (real roots only).
Demo 3: Complex Roots of a Quintic
$x^5 + 1 = 0$ has one real root $x = -1$ and four complex roots.
Since no closed-form solution exists for degree 5 or higher (Abel-Ruffini theorem),
findAllRoots automatically selects the Jenkins-Traub method.
Source Code and How to Run
example_roots.cpp (full source code)
// example_roots.cpp — Root Finding demo
#include <math/roots/root_finding.hpp>
#include <iostream>
#include <iomanip>
using namespace calx;
int main() {
std::cout << std::setprecision(16);
// --- Demo 1: Brent's method ---
std::cout << "=== Brent's Method: f(x) = x^2 - 2 ===\n";
auto result = brent_method(
[](double x) { return x * x - 2.0; },
1.0, 2.0
);
std::cout << "root = " << result.value << "\n";
std::cout << "expected = " << std::sqrt(2.0) << "\n";
std::cout << "converged: " << (result.converged ? "true" : "false") << "\n";
std::cout << "iterations: " << result.iterations << "\n";
// --- Demo 2: Cubic roots ---
std::cout << "\n=== Cubic: x^3 - 6x^2 + 11x - 6 ===\n";
Polynomial<double> p = {-6.0, 11.0, -6.0, 1.0};
auto roots = findAllRoots(p);
for (size_t i = 0; i < roots.size(); ++i)
std::cout << "root[" << i << "] = " << roots[i] << "\n";
std::cout << "\nVerification:\n";
for (auto& r : roots)
std::cout << " p(" << r.real() << ") = " << p(r.real()) << "\n";
// --- Demo 3: Quintic ---
std::cout << "\n=== Quintic: x^5 + 1 ===\n";
Polynomial<double> q = {1.0, 0.0, 0.0, 0.0, 0.0, 1.0};
auto roots5 = findAllRoots(q);
for (size_t i = 0; i < roots5.size(); ++i)
std::cout << "root[" << i << "] = " << roots5[i] << "\n";
std::cout << "\nAll on unit circle:\n";
for (size_t i = 0; i < roots5.size(); ++i)
std::cout << " |root[" << i << "]| = " << abs(roots5[i]) << "\n";
return 0;
}
For API details, see the Root Finding API Reference.
Build and Run
cd calx
mkdir build && cd build
cmake .. -G "Visual Studio 17 2022" -A x64
cmake --build . --config Release --target example-roots
examples\Release\example-roots.exe