fcnDerivative

Computes the first, second, or third derivative of a user-supplied function.

Synopsis

fcnDerivative (fcn, x)

Required Arguments

float fcn(x) (Input)
User-supplied function whose derivative at x will be computed.
float x (Input)
Point at which the derivative will be evaluated.

Return Value

An estimate of the first, second or third derivative of fcn at x. If no value can be computed, NaN is returned.

Optional Arguments

order, int (Input)

The order of the desired derivative (1, 2 or 3).

Default: order = 1.

initialStepsize, float (Input)

Beginning value used to compute the size of the interval for approximating the derivative. Stepsize must be chosen small enough that fcn is defined and reasonably smooth in the interval (x − 4.0 × initialStepsize, x + 4.0 × initialStepsize), yet large enough to avoid roundoff problems.

Default: initialStepsize = 0.01

relativeError, float (Input)

The relative error desired in the derivative estimate. Convergence is assumed when \((2/3)|d_2 ‑ d_1|\) < relativeError, for two successive derivative estimates, \(d_1\) and \(d_2\).

Default: relativeError = \(\sqrt[4]{\varepsilon}\) where ɛ is the machine precision.

Description

The function fcnDerivative produces an estimate to the first, second, or third derivative of a function. The estimate originates from first computing a spline interpolant to the input function using value within the interval (x − 4.0 × initialStepsize, x + 4.0 × initialStepsize), then differentiating the spline at x.

Examples

Example 1

This example obtains the approximate first derivative of the function \(f(x) = -2\sin(3x/2)\) at the point \(x = 2\).

from __future__ import print_function
from numpy import *
from pyimsl.math.fcnDerivative import fcnDerivative


def fcn(x):
    return -2.0 * sin(1.5 * x)


x = 2.0
deriv = fcnDerivative(fcn, x)
print("f'(x)   = %7.4f" % (deriv))

Output

f'(x)   =  2.9700

Example 2

This example obtains the approximate first, second, and third derivative of the function \(f(x) = ‑2\sin(3x/2)\) at the point \(x = 2\).

from __future__ import print_function
from numpy import *
from pyimsl.math.fcnDerivative import fcnDerivative


def fcn(x):
    return -2.0 * sin(1.5 * x)


x = 2.0

deriv1 = fcnDerivative(fcn, x)
print("f'(x)   = %7.3f, error = %5.2e" %
      (deriv1, fabs(deriv1 + 3.0 * cos(1.5 * x))))

deriv2 = fcnDerivative(fcn, x, order=2)
print("f''(x)  = %7.4f, error = %5.2e" %
      (deriv2, fabs(deriv2 - 4.5 * sin(1.5 * x))))

deriv3 = fcnDerivative(fcn, x, order=3)
print("f'''(x) = %7.4f, error = %5.2e" %
      (deriv3, fabs(deriv3 - 6.75 * cos(1.5 * x))))

Output

f'(x)   =   2.970, error = 6.97e-12
f''(x)  =  0.6350, error = 3.90e-11
f'''(x) = -6.6824, error = 1.38e-07

Fatal Errors

IMSL_STOP_USER_FCN

Request from user supplied function to stop algorithm.

User flag = “#”.