The OpenD Programming Language

diff

Calculate the derivative of a function. This function uses Ridders' method of extrapolating the results of finite difference formulas for consecutively smaller step sizes, with an improved stopping criterion described in the Numerical Recipes books by Press et al.

This method gives a much higher degree of accuracy in the answer compared to a single finite difference calculation, but requires more function evaluations; typically 6 to 12. The maximum number of function evaluations is 24.

diff
(
T
)
(
const T x
,
const T h
,
const T factor = T(2).sqrt
,
const T safe = 2
)

Parameters

f

The function of which to take the derivative.

x T

The point at which to take the derivative.

h T

A "characteristic scale" over which the function changes.

factor T

Stepsize is decreased by factor at each iteration.

safe T

Return when error is SAFE worse than the best so far.

References:

  • C. J. F. Ridders, Accurate computation of F'(x) and F'(x)F''(x). Advances in Engineering Software, vol. 4 (1982), issue 2, p. 75.
  • W. H. Press, S. A. Teukolsky, W. T. Vetterling, and B. P. Flannery, Numerical Recipes in C++ (2nd ed.). Cambridge University Press, 2003.

Examples

import mir.math.common;

auto f(double x) { return exp(x) / (sin(x) - x ^^ 2); }
auto d(double x) { return -(exp(x) * ((x - 2) * x - sin(x) + cos(x)))/(x^^2 - sin(x))^^2; }
auto r = diff!f(1.0, 0.01);
assert (approxEqual(r.value, d(1)));

Meta