deriv: Numerical Derivatives via Finite Differences

derivR Documentation

Numerical Derivatives via Finite Differences

Description

Numerical Derivatives via Finite Differences

Usage

fd_deriv1(f, x, i, h, fd_type)

fd_deriv2(f, x, i, j, h_i, h_j, fd_type)

deriv1(f, x, i, args, fd_type)

deriv2(f, x, i, j, args, fd_type)

Arguments

f

Function to differentiate.

x

Scalar at which to evaluate the derivative.

i

First coordinate to differentiate.

h

Step size in the first coordinate.

fd_type

Type of derivative: 0 for symmetric difference, 1 for forward difference, and 2 for backward difference.

j

Second coordinate to differentiate.

h_i

Step size in the first coordinate.

h_j

Step size in the second coordinate.

args

List of additional arguments from the function richardson_args.

Value

fd_deriv1 and fd_deriv2 return a single numeric value corresponding to the first and second derivative via finite differences. deriv1 and deriv2 return a list with the form of a richardson_result described in section "Richardson Extrapolated Finite Differences" of the package vignette.

Examples

args = richardson_args()

f = sin   # Try 2nd derivatives of a univariate function
x0 = 0.5
print(-sin(x0))  ## Exact answer for f''(x0)

fd_deriv2(f, x0, i = 0, j = 0, h_i = 0.001, h_j = 0.001, fd_type = 0)
fd_deriv2(f, x0, i = 0, j = 0, h_i = 0.001, h_j = 0.001, fd_type = 1)
fd_deriv2(f, x0, i = 0, j = 0, h_i = 0.001, h_j = 0.001, fd_type = 2)

deriv2(f, x0, i = 0, j = 0, args, fd_type = 0)

# Try 2nd derivatives of a bivariate function
f = function(x) { sin(x[1]) + cos(x[2]) }
x0 = c(0.5, 0.25)

print(-sin(x0[1]))  ## Exact answer for f_xx(x0)
print(-cos(x0[2]))  ## Exact answer for f_yy(x0)
print(0)         ## Exact answer for f_xy(x0,y0)

numDeriv::hessian(f, x0)

fd_deriv2(f, x0, i = 0, j = 0, h_i = 0.001, h_j = 0.001, fd_type = 0)
fd_deriv2(f, x0, i = 0, j = 0, h_i = 0.001, h_j = 0.001, fd_type = 1)
fd_deriv2(f, x0, i = 0, j = 0, h_i = 0.001, h_j = 0.001, fd_type = 2)

fd_deriv2(f, x0, i = 0, j = 1, h_i = 0.001, h_j = 0.001, fd_type = 0)
fd_deriv2(f, x0, i = 0, j = 1, h_i = 0.001, h_j = 0.001, fd_type = 1)
fd_deriv2(f, x0, i = 0, j = 1, h_i = 0.001, h_j = 0.001, fd_type = 2)

fd_deriv2(f, x0, i = 1, j = 1, h_i = 0.001, h_j = 0.001, fd_type = 0)
fd_deriv2(f, x0, i = 1, j = 1, h_i = 0.001, h_j = 0.001, fd_type = 1)
fd_deriv2(f, x0, i = 1, j = 1, h_i = 0.001, h_j = 0.001, fd_type = 2)

deriv2(f, x0, i = 1, j = 1, args, fd_type = 0)
deriv2(f, x0, i = 1, j = 1, args, fd_type = 1)
deriv2(f, x0, i = 1, j = 1, args, fd_type = 2)


fntl documentation built on April 4, 2025, 1:53 a.m.