Search code examples
c++numerical-methodsderivative

How can I estimate the first derivative of an evaluated univariate function in C++?


I have a two vectors:

  • Coordinates along an axis, x;
  • An evaluation of a function on those coordinates, f(x).

and I want to compute an estimate of the first derivative of f at these coordinates.

The function is a descriptor of a wavefunction and x is the dihedral angle.

Because the result vector must have the same length as the two existing vectors, I cannot use a manual implementation based on Newton's difference quotient.

In Python, I can obtain such an estimate using the scipy library:

spline = UnivariateSpline(X, Y, k=4, s=0)
sd = spline.derivative(n=1)

Perhaps I can do something similar in C++?


Solution

  • I'd start with pchip.

    Example:

    #include <boost/math/interpolators/pchip.hpp>
    // ...
    using boost::math::interpolators::pchip;
    auto f = pchip(std::move(x), std::move(y));
    double t = 3.2;
    std::cout << "f(" << t << " = " << f(t) << ", f'(" << t << ") = " << f.prime(t) << "\n";
    

    If you don't like the "character" of pchip, then you have many other options.