MATLAB: How to eliminate the NaN

nanwhile loop

I am writing a script to find the cosine of a value using the Taylor Series, using a while loop.
x = input('Angle in Radians:');
d=cos(x);
f=1;
difference = d - f;
difference = abs(difference);
threshold = .0001;
n = 0;
while difference > threshold
n = n + 1;
f = ((-1)^n)*((x^(2*n))/(factorial(2*n)));
difference = d - f;
difference = abs(difference);
endwhile
fprintf('The cosine of %f is %0.3f\n', x, f)
The main issue I am having is the f value is spitting out a NaN. All I could think of was that my equation was somehow dividing by zero but I cannot figure out where. My experience with Matlab is very limited, so if I missed something, it would be very appreciated if someone could point it out.

Best Answer

x = input('Angle in Radians:');
d=cos(x);
f=1;
difference = d - f;
difference = abs(difference);
threshold = .0001;
n = 0;
while difference > threshold
n = n + 1;
f = f+((-1)^n)*((x^(2*n))/(factorial(2*n)));%need f=f+...
difference = abs(d - f);%easier
end%just end
fprintf('The cosine of %f is %0.3f\n', x, f)