Using python:
Find the Taylor polynomials of cos(x) about 0, i.e., p_n(x) where n=1, 3, 5(no programming here). For the domain -pi to pi, graph these 3 polynomials along with cos(x) all versus x. Use numpy in your program. Generate the vector x by
import numpy as N
x = np.arange( -3.14 , 3.14 , 0.01)
Save your graph to a pdf file. Use different symbols for each plot likes “+” and “o”s. Provide a legend and title. Use an x-label and y-label for axes.
Adjust the size of the plot. Give some axis parameters.
What do you observe about the graph?
Expert Answer
Tailor Seriese formula for cos(x):
Python 3 code:
import math
import matplotlib.pyplot as plt
import numpy as np
def p_1(x):
y = np.arange( -3.14 , 3.14 , 0.01);
for j in range(0,len(x)):
v = 0;
for i in range(0,2):
v = v + ( ( (-1)**i) * ((x[j])**(2*i)) / (math.factorial(2*i)) );
y[j] = v
return y
def p_3(x):
y = np.arange( -3.14 , 3.14 , 0.01);
for j in range(0,len(x)):
v = 0;
for i in range(0,4):
v = v + ( ( (-1)**i) * ((x[j])**(2*i)) / (math.factorial(2*i)) );
y[j] = v
return y
def p_5(x):
y = np.empty(len(x));
for j in range(0,len(x)):
v = 0;
for i in range(0,6):
v = v + ( ( (-1)**i) * ((x[j])**(2*i)) / (math.factorial(2*i)) );
y[j] = v
return y
def coss(x):
y = np.cos(x);
return y
x = np.arange( -3.14 , 3.14 , 0.01)
plt.plot(x,p_5(x),color = “blue”, label = “p_5(x)”)
plt.plot(x,p_3(x),color = “red”, label = “p_3(x)”)
plt.plot(x,p_1(x),color = “green”, label = “p_1(x)”)
plt.plot(x,coss(x),color = “yellow”, label = “cos(x)”)
plt.xlabel(‘x’)
plt.legend(loc = ‘upper left’)
plt.show()
Sample Output: