Homework 14

f(x) = 1/(1−x)

x <- seq(-0.9, 0.9, by = 0.1)
n <- 10
result <- matrix(0, nrow = length(x), ncol = n)

for (i in 1:length(x)) {
  for (j in 0:(n-1)) {
    result[i, j+1] <- x[i]^j
  }
}

coefficients <- rep(1, n)
for (j in 1:n) {
  coefficients[j] <- sum(x^(j-1))
}

taylor_series <- result %*% coefficients

# plot the function and its Taylor series
plot(x, 1/(1-x), type = "l", ylim = c(-10, 10), ylab = "f(x)")
lines(x, taylor_series, col = "red")
legend("topright", c("f(x)", "Taylor series"), lty = 1, col = c("black", "red"))

f(x) = e^x

x <- seq(-5, 5, by = 0.1)
n <- 10
result <- matrix(0, nrow = length(x), ncol = n)

for (i in 1:length(x)) {
  for (j in 0:(n-1)) {
    result[i, j+1] <- x[i]^j / factorial(j)
  }
}

taylor_series <- rowSums(result)

# plot the function and its Taylor series
plot(x, exp(x), type = "l", ylim = c(-10, 100), ylab = "f(x)")
lines(x, taylor_series, col = "red")
legend("topright", c("f(x)", "Taylor series"), lty = 1, col = c("black", "red"))

f(x) = ln(1 + x)

x <- seq(-0.9, 0.9, by = 0.1)
n <- 10
result <- matrix(0, nrow = length(x), ncol = n)

for (i in 1:length(x)) {
  for (j in 1:n) {
    result[i, j] <- (-1)^(j+1) * x[i]^j / j
  }
}

taylor_series <- rowSums(result)

# plot the function and its Taylor series
plot(x, log(1+x), type = "l", ylim = c(-5, 2), ylab = "f(x)")
lines(x, taylor_series, col = "red")
legend("topright", c("f(x)", "Taylor series"), lty = 1, col = c("black", "red"))

f(x) = x^(1/2)

x <- seq(0.9, 1.1, by = 0.01)
n <- 10
result <- matrix(0, nrow = length(x), ncol = n)

for (i in 1:length(x)) {
  for (j in 0:(n-1)) {
    result[i, j+1] <- ((-1)^j * factorial(2*j) * (x[i]-1)^j) / (4^j * factorial(j)^2)
  }
}

taylor_series <- rowSums(result)

# plot the function and its Taylor series
plot(x, sqrt(x), type = "l", ylim = c(0, 2), ylab = "f(x)")
lines(x, taylor_series, col = "red")
legend("bottomright", c("f(x)", "Taylor series"), lty = 1, col = c("black", "red"))