How can I eliminate the NaN?

4 Ansichten (letzte 30 Tage)
Landen Little
Landen Little am 3 Apr. 2020
Kommentiert: Landen Little am 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.

Akzeptierte Antwort

David Hill
David Hill am 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 Kommentar
Landen Little
Landen Little am 3 Apr. 2020
Yes! Thank you, that is definitely what I missed

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by