We can use the taylor function included in the
calculus library within R for this. The above functon is
valid everywhere except \(x=1\)
f1 <- function(x){ 1 / (1 - x)}
taylor(f1, var="x", order=4)
## $f
## [1] "(1) * 1 + (1.00000000000064) * x^1 + (0.999999999867712) * x^2 + (0.999994567795319) * x^3 + (0.999693345466748) * x^4"
##
## $order
## [1] 4
##
## $terms
## var coef degree
## 0 1 1.0000000 0
## 1 x^1 1.0000000 1
## 2 x^2 1.0000000 2
## 3 x^3 0.9999946 3
## 4 x^4 0.9996933 4
This function is valid everywhere within \((-\infty, \infty)\). We can calulate the Taylor series to n=4
# f1 <- function(x){ 1 / (1 - x)}
taylor("exp(x)", var="x", order=4)
## $f
## [1] "(1) * 1 + (1) * x^1 + (0.5) * x^2 + (0.166666666666667) * x^3 + (0.0416666666666667) * x^4"
##
## $order
## [1] 4
##
## $terms
## var coef degree
## 0 1 1.00000000 0
## 1 x^1 1.00000000 1
## 2 x^2 0.50000000 2
## 3 x^3 0.16666667 3
## 4 x^4 0.04166667 4
This function is only defined when \(x > -1\). We can compute the Taylor series, centered at 0
f3 <- function(x){log(1 + x)}
(t3 <- taylor(f3, var=0, order=4))
## $f
## [1] "(0.999999999994524) * x1^1 + (-0.499999999988492) * x1^2 + (0.333332558064607) * x1^3 + (-0.249961920878393) * x1^4"
##
## $order
## [1] 4
##
## $terms
## var coef degree
## 0 1 0.0000000 0
## 1 x1^1 1.0000000 1
## 2 x1^2 -0.5000000 2
## 3 x1^3 0.3333326 3
## 4 x1^4 -0.2499619 4
The above function is only valid and differentiable over the reals when \(x > 0\). We can calculate the Taylor series centered at \(x=1\), as thatโs a valid point of reference
f4 <- function(x){sqrt(x)}
(t4 <- taylor(f4, var=1, order=4))
## $f
## [1] "(1) * 1 + (0.499999999993442) * (x1-1)^1 + (-0.125000000007528) * (x1-1)^2 + (0.0624999125751056) * (x1-1)^3 + (-0.0390585237804083) * (x1-1)^4"
##
## $order
## [1] 4
##
## $terms
## var coef degree
## 0 1 1.00000000 0
## 1 (x1-1)^1 0.50000000 1
## 2 (x1-1)^2 -0.12500000 2
## 3 (x1-1)^3 0.06249991 3
## 4 (x1-1)^4 -0.03905852 4