How can I eliminate the NaN?
4 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
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)
More Answers (0)
See Also
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!