8.8.1 to create the Taylor series of the given functons.
f <- function(x) {
return(exp(-x))
}
taylor_series <- function(x, n) {
sum <- 0
for (i in 0:n) {
sum <- sum + (f(i) / factorial(i)) * x^i
}
return(sum)
}
x_values <- c(0, 1, 2, 3)
n_values <- c(1, 2, 3, 4)
for (x in x_values) {
cat("x =", x, "\n")
for (n in n_values) {
cat("n =", n, ": ", taylor_series(x, n), "\n")
}
cat("\n")
}
## x = 0
## n = 1 : 1
## n = 2 : 1
## n = 3 : 1
## n = 4 : 1
##
## x = 1
## n = 1 : 1.367879
## n = 2 : 1.435547
## n = 3 : 1.443845
## n = 4 : 1.444608
##
## x = 2
## n = 1 : 1.735759
## n = 2 : 2.006429
## n = 3 : 2.072812
## n = 4 : 2.085023
##
## x = 3
## n = 1 : 2.103638
## n = 2 : 2.712647
## n = 3 : 2.936689
## n = 4 : 2.998504