How to approximate cosine with taylor series expansion and while loops

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);

4 Comments

Tell us what the errors are, if you are having errors! And don't name a variable 'error' (or any other name of an existing function) otherwise you can get some potentially unexpected behaviour. Probably not here, due to scope, but it is good practice to just make sure you do not reuse function names as variables as it hides the function within the scope of the variable.
this is the error I'm currently getting: Subscript indices must either be real positive integers or logicals. Error in HW2_Johnson (line 7) terms(count)=(-1)^(count)*(x^(2*count))/(factorial(count));
I have to solve to set accuracy which I was under the impression that was a while loop

Sign in to comment.

 Accepted 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 ...

4 Comments

What does your code do with an input of pi/2?
im having a similar problem when you enter pi/2. what is your suggestion.
@Miguel: Open up a new question, post your code, and describe the problems you are having.

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!