Matlab Taylor Series for cos

  • #1
1
0

Homework Statement



Write a user-defined function that determines cos(x) using Taylor Series expansion
Stop adding terms when estimated error, E<=.000001

Homework Equations



sum Sn = Sn-1 + an
E = | (Sn - Sn-1)/Sn-1 |

The Attempt at a Solution



function y = cosTaylor(x)
Sn=1;
Snm1=0;
n=2;
xr=x*pi/180;
E=1;
while E >= .000001
an=(-1)^n*xr^(2*n)/(factorial(2*n));
Snm1=Sn;
Sn=Snm1+an;
n=n+1;
E=abs((Sn-Snm1)/Snm1);
end


This gives values too large compared to what they should be.
I really don't understand why this doesn't work.
Any help is appreciated.
Thanks in advance!
 
Physics news on Phys.org
  • #2
Why did you start n as 2? It should be 1, since in your formula for an you use 2*n.
Starting with n = 2, your first term is added to 1, making the cosine greater than unity. The following terms have absolute values smaller than the first, so you will have always too large results.
 

Suggested for: Matlab Taylor Series for cos

Replies
3
Views
587
Replies
6
Views
262
Replies
1
Views
799
Replies
5
Views
885
Replies
10
Views
977
Replies
4
Views
2K
Replies
3
Views
741
Replies
3
Views
757
Replies
1
Views
629
Back
Top