numerics 0.1.0
Loading...
Searching...
No Matches
Analysis Examples

Analysis routines provide scalar quadrature and root finding. They are intended for small numerical subproblems inside larger solvers and experiments.

Composite Quadrature

#include <numerics.hpp>
auto f = [](double x) {
return std::exp(-x * x);
};
double q1 = num::trapz(f, 0.0, 1.0, 4096);
double q2 = num::simpson(f, 0.0, 1.0, 4096);
double q3 = num::romberg(f, 0.0, 1.0, 1e-12);
real trapz(ScalarFn f, real a, real b, idx n=100, Backend backend=Backend::seq)
Trapezoidal rule with n panels.
real simpson(ScalarFn f, real a, real b, idx n=100, Backend backend=Backend::seq)
Simpson's 1/3 rule with n panels (n must be even)
real romberg(ScalarFn f, real a, real b, real tol=1e-10, idx max_levels=12)
Romberg integration (Richardson extrapolation on trapezoidal rule)
Umbrella include for the numerics library.

Backend::omp parallelizes the panel sums in trapz and simpson.

double q = num::simpson(f, 0.0, 1.0, 1 << 20, num::Backend::omp);

Gauss-Legendre Rule

auto p = [](double x) {
return x * x * x * x;
};
double exact_for_degree_4 = num::gauss_legendre(p, -1.0, 1.0, 3);
real gauss_legendre(ScalarFn f, real a, real b, idx p=5)
Gauss-Legendre quadrature (exact for polynomials up to degree 2p-1)

With p points, the rule is exact for polynomials through degree (2p-1).

Bracketed Roots

auto g = [](double x) {
return std::cos(x) - x;
};
num::RootResult r = num::brent(g, 0.0, 1.0, 1e-12);
RootResult brent(ScalarFn f, real a, real b, real tol=1e-10, idx max_iter=1000)
Brent's method (bisection + secant + inverse quadratic interpolation)
Definition roots.cpp:61

Use Brent's method when a sign-changing bracket is available.

Newton Iteration

auto f0 = [](double x) { return x * x - 2.0; };
auto df = [](double x) { return 2.0 * x; };
num::RootResult r = num::newton(f0, df, 1.0, 1e-12);
RootResult newton(ScalarFn f, ScalarFn df, real x0, real tol=1e-10, idx max_iter=1000)
Newton-Raphson method.
Definition roots.cpp:30

Newton iteration is appropriate when the derivative is available and the starting value is in the local basin of attraction.