This is a quick solution to one of the exercises of homework #6, i.e.Â the Taylor series for the function: $f(x) = sin(x)$

Let us define an R-function for each approximation:

#Taylor approximation of order 0
sinXorder0 <- function(x, x0=0) sin(x0)
#Taylor approximation of order 1
sinXorder1 <- function(x, x0=0) sin(x0) + (x - x0)*cos(x0)
#Taylor approximation of order 2
sinXorder2 <- function(x, x0=0)
sin(x0) + (x - x0)*cos(x0) -
(x - x0)^2 * sin(x0) / factorial(2)
#Taylor approximation of order 3
sinXorder3 <- function(x, x0=0)
sin(x0) + (x - x0)*cos(x0) -
(x - x0)^2 * sin(x0) / factorial(2) -
(x - x0)^3 * cos(x0) / factorial(3)
#Taylor approximation of order 4
sinXorder4 <- function(x, x0=0)
sin(x0) + (x - x0)*cos(x0) -
(x - x0)^2 * sin(x0) / factorial(2) -
(x - x0)^3 * cos(x0) / factorial(3) +
(x - x0)^4 * sin(x0) / factorial(4)
#Taylor approximation of order 5
sinXorder5 <- function(x, x0=0)
sin(x0) + (x - x0)*cos(x0) -
(x - x0)^2 * sin(x0) / factorial(2) -
(x - x0)^3 * cos(x0) / factorial(3) +
(x - x0)^4 * sin(x0) / factorial(4) +
(x - x0)^5 * cos(x0) / factorial(5)
#the Vectorize function is needed in order to evaluate the function
#separately for each element of the input vector
sinXorder0vec <- Vectorize(expXorder0, vectorize.args="x")
#vector of points in which the function is evaluated
abscissa <- seq(-5, 5, by=0.1)
#rappresento la funzione da approssimare usando una linea nera
plot(abscissa, sin(abscissa), type="l",
col="black", xlab="x", ylab="f(x)",
main=expression(paste("f(x)=",sin(x))))
#the order 0 approximation is plotted using a red line
lines(abscissa, sinXorder0vec(abscissa), col="red")
#the order 1 approximation is plotted using a blue line
lines(abscissa, sinXorder1(abscissa), col="blue")
#the order 2 approximation is plotted using a green line
lines(abscissa, sinXorder2(abscissa), col="green")
#the order 3 approximation is plotted using a magenta line
lines(abscissa, sinXorder3(abscissa), col="magenta")
#the order 4 approximation is plotted using a brown line
lines(abscissa, sinXorder4(abscissa), col="brown")
#the order 5 approximation is plotted using a orange line
lines(abscissa, sinXorder5(abscissa), col="orange")

What happens if we change the value $$x_0$$ in which the function is approximated? Here is the answer for the case $$x_0 = 3$$:

plot(abscissa, sin(abscissa), type="l",
col="black", xlab="x", ylab="f(x)",
main=expression(paste("f(x)=",sin(x))))
lines(abscissa, sinXorder0vec(abscissa, x0=3), col="red")
lines(abscissa, sinXorder1(abscissa, x0=3), col="blue")
lines(abscissa, sinXorder2(abscissa, x0=3), col="green")
lines(abscissa, sinXorder3(abscissa, x0=3), col="magenta")
lines(abscissa, sinXorder4(abscissa, x0=3), col="brown")
lines(abscissa, sinXorder5(abscissa, x0=3), col="orange")