How to approximate cosine with taylor series expansion and while loops
Show older comments
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
Adam
on 22 Jan 2018
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.
Erin Johnson
on 22 Jan 2018
Edited: Erin Johnson
on 22 Jan 2018
Birdman
on 22 Jan 2018
You have to use while loop?
Erin Johnson
on 22 Jan 2018
Accepted Answer
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!