Improving Cosine Approximation Using Taylor Series in Matlab

Click For Summary
The discussion focuses on creating a user-defined function in Matlab to approximate cos(x) using the Taylor Series expansion, stopping when the estimated error is less than or equal to 0.000001. The initial implementation incorrectly starts the term index at n=2, leading to inflated cosine values. The correct approach should start with n=1 to ensure the first term is accurately included in the calculation. This adjustment will prevent the function from consistently producing values greater than one. Properly implementing the Taylor Series will yield more accurate results for the cosine approximation.
StaloyT
Messages
1
Reaction score
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
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.
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 9 ·
Replies
9
Views
4K
Replies
5
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
2
Views
1K
Replies
6
Views
3K
Replies
4
Views
5K