Why can't I get an output when I am trying to find Cosine of 180 radians using Taylor series expansion.

sum= double(1);
sign=1;
for n=2:2:1000
sign = -sign;
form = ((Rad).^n)/factorial(n);
sum = sum + (sign*(form));
if form <= 0.000000001
break;
end
end
CosFormula = sum

3 Comments

Could you please clarify what you are trying to do? The code runs and and the CosFormula variable has a the expected value. Are you trying to use it as a function?
"Rad" is undefined.
Furthermore, you should not build x^n/n! anew in each step because you will arrive at Infinity/Infinity quite soon for Rad>1. Note that form_new = form_old*x^2/((2*n-1)*2*n).
What are you trying to calculate - cos(180) or cos(pi) ? Note that the argument in the Taylor series expansion is in radians, not in degrees.
Best wishes
Torsten.
Do not use sum or sign as variable names. They both are the names of frequently used matlab functions and having a variable with the same name means you can't use the functions anymore.

Answers (0)

This question is closed.

Asked:

on 9 Feb 2016

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!