# Plotting error graph Taylor series for $\cos x$ (means plotting $|\cos(x)-\sum_{i=1}^{N}(taylor)|$)

The question is: "it is known that for $-\infty<x<\infty$ cos(x) can be written as Maclaurin series in following way: [there example until $\frac{x^6}{6!}$] plot the error graph when number of iterations (N) is horizonal axis and the error (E) is the vertical axis. e.g error for n=1 is $E=|cos(x)-1|$". How can I write it? I tried this code

function question2 (x,N)
sum=0;
s=1;
for i=0:2:N;
sum=sum+((s*(x).^(i))/factorial(i));
s=s*(-1);
end
y=abs(cos(x)-sum);
plot(x,y)
end


But it gives a monotonically increasing graph. I asked a friend for help and he suggested this code:

function question2 (x,N)
vect=2:2:N;
summing=1;
s=-1;
index=1;
vecty=zeros(floor(N/2));
for k=2:2:N;
summing=summing+((s*(x).^(k))/factorial(k));
vecty(k)=abs(cos(x)-summing);
index=index+1;
s=s*(-1);
end
plot(vect,vecty)
end


This code does not work at all. Where is the error in code, and how can it be solved?

-
Try putting the multiple of $s$ outside some brackets so you don't accidentally take powers of that too. – muzzlator Mar 26 '13 at 17:30
Also in the interest of efficiency, $$\dfrac{x^{n+2}}{(n+2)!} / \dfrac{x^n}{n!} = \dfrac{x^2}{(n+1)(n+2)}$$ meaning you don't need to compute powers and factorial every time. – muzzlator Mar 26 '13 at 17:33
@muzzlator putting s outside doesn't work. and how can I use whta you wrote about the factorials ? – user65985 Mar 26 '13 at 18:25
That stuff should only be worried about once you get the base code working. I just noticed you are plotting the error, which very well could be monotonic. You might not be having a problem at all. Try plotting just "summing" – muzzlator Mar 26 '13 at 18:32
the question was to plot absolute value of cossine - the taylor and not the taylor (means the error and not the maclourian series...) – user65985 Mar 26 '13 at 18:55