The function taylor
provides a convenient way to compute the Taylor series of arbitrary
unidimensional or multidimensional functions. The mathematical function
can be specified both as a character
string or as a
function
. Symbolic or numerical methods are applied
accordingly. For univariate functions, the n-th order Taylor approximation
centered in x0 is
given by:
$$ f(x) \simeq \sum_{k=0}^n\frac{f^{(k)}(x_0)}{k!}(x-x_0)^k $$
where f(k)(x0) denotes the k-th order derivative evaluated in x0. By using multi-index notation, the Taylor series is generalized to multidimensional functions with an arbitrary number of variables:
$$ f(x) \simeq \sum_{|k|=0}^n\frac{f^{(k)}(x_0)}{k!}(x-x_0)^k $$
where now x = (x1, …, xd) is the vector of variables, k = (k1, …, kd) gives the order of differentiation with respect to each variable $f^{(k)}=\frac{\partial^{(|k|)}f}{\partial^{(k_1)}_{x_1}\cdots \partial^{(k_d)}_{x_d}}$, and:
|k| = k1 + ⋯ + kd k! = k1!⋯kd! xk = x1k1⋯xdkd
The summation runs for 0 ≤ |k| ≤ n and identifies the set
{(k1, ⋯, kd) : k1 + ⋯kd ≤ n}
that corresponds to the partitions of the integer n. These partitions can be computed
with the function partitions
that is included in the package and optimized in C++
for
speed and flexibility. For example, the following call generates the
partitions needed for the 2-nd order
Taylor expansion for a function of 3
variables:
partitions(n = 2, length = 3, fill = TRUE, perm = TRUE, equal = FALSE)
#> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#> [1,] 0 0 0 1 0 0 2 0 1 1
#> [2,] 0 0 1 0 0 2 0 1 0 1
#> [3,] 0 1 0 0 2 0 0 1 1 0
Based on these partitions, the function taylor
computes the corresponding derivatives and builds the Taylor series. The
output is a list
containing the Taylor series, the order of
the expansion, and a data.frame
containing the variables,
coefficients and degrees of each term in the Taylor series.
taylor("exp(x)", var = "x", order = 2)
#> $f
#> [1] "(1) * 1 + (1) * x^1 + (0.5) * x^2"
#>
#> $order
#> [1] 2
#>
#> $terms
#> var coef degree
#> 0 1 1.0 0
#> 1 x^1 1.0 1
#> 2 x^2 0.5 2
By default, the series is centered in x0 = 0 but the function
also supports x0 ≠ 0, the multivariable
case, and the approximation of user defined R
functions
.
f <- function(x, y) log(y)*sin(x)
taylor(f, var = c(x = 0, y = 1), order = 2)
#> $f
#> [1] "(0.999999999969436) * x^1*(y-1)^1"
#>
#> $order
#> [1] 2
#>
#> $terms
#> var coef degree
#> 0,0 1 0 0
#> 0,1 (y-1)^1 0 1
#> 1,0 x^1 0 1
#> 0,2 (y-1)^2 0 2
#> 2,0 x^2 0 2
#> 1,1 x^1*(y-1)^1 1 2
Guidotti E (2022). “calculus: High-Dimensional Numerical and Symbolic Calculus in R.” Journal of Statistical Software, 104(5), 1-37. doi:10.18637/jss.v104.i05
A BibTeX entry for LaTeX users is