How can I eliminate the NaN?

4 views (last 30 days)
Landen Little
Landen Little on 3 Apr 2020
Commented: Landen Little on 3 Apr 2020
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.

Accepted Answer

David Hill
David Hill on 3 Apr 2020
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)
  1 Comment
Landen Little
Landen Little on 3 Apr 2020
Yes! Thank you, that is definitely what I missed

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!