I have a simple question. I want to write Taylor series expansion for cos(x). And I wrote that codes
x=input('Please input an angle in degrees: ');
cosx=1;
for i=1:1:x
addterm = (-1)^i*(x.^(2*i))/factorial(2*i);
cosx = cosx + addterm;
end
a=['The value of cosine of ',num2str(x),' degrees is ', num2str(cosx)];
disp(a)
But that code did not give true result.Why?
The Taylor series you use needs x
to be expressed in radians. After the input
multiply x
by π/180
to convert degrees to radians. Also you need to have many iterations, not just x
. Try for i=1:1:10
because factorial grows very fast.