How can I eliminate the NaN?

4 vues (au cours des 30 derniers jours)
Landen Little
Landen Little le 3 Avr 2020
Commenté : Landen Little le 3 Avr 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.

Réponse acceptée

David Hill
David Hill le 3 Avr 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 commentaire
Landen Little
Landen Little le 3 Avr 2020
Yes! Thank you, that is definitely what I missed

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by