MATLAB: How to approximate cosine with taylor series expansion and while loops

homeworkwhile loop

I have to approximate cos(x) using taylor series expansion with a while loop to run until .00001 accuracy. the taylor series expansion for cos(x) is sum from n=0 –> inf (((-1)^n)*x^(2n))/((2n)!) I have included the code that I've been attempting but I keep having errors with the while loop
x=input('Enter the value of the angle in radians: ');
error=1;
count=0;
while error>=1*(10^-4)
count=count+1;
terms(count)=(-1)^(count)*(x^(2*count))/(factorial(count));
Cosx=sum(terms);
error=abs((cos(x)-Cosx)/cos(x));
end
fprintf('cos(%d)=%6.6f \n',x,sn);

Best Answer

Taylor series for cos(x) is
1 - x^2/2! + x^4/4! - x^6/6! + ...
So, you are missing that first term of 1 and your x exponent value of "2*count" is not matching your factorial value of "count" when compared to this series (they should be the same value ... e.g. the "2n" from the formula you post above).
To correct this, make the first terms value 1, e.g. put this line before the while loop
terms(1) = 1;
Then bump up the terms indexing so you don't overwrite that first value, e.g.,
terms(count+1) = ...
Then correct that factorial argument so it matches the exponent, e.g.,
.../factorial(2*count)
Since you are apparently running this in a script, you need to clear terms from your workspace before running this script. Otherwise you will be left with your old terms result when you start this script. Either put all of this code inside of a function so that you always start with a clean workspace (my preferred approach), or you can just make sure terms is cleared first. E.g. put this line at the top of your script:
clear terms
There is one other problem in your code which I will let you find ...