Question about Taylor Series While loop.
이전 댓글 표시
I'm completely stuck on this While Loop using Taylor Series.
x = input('Input the angle in radians: ');
Cos_Estimate = 0;
k = 0;
Errrr = 1
while Errrr > .000001
if mod(k,2)
Sign = 1;
else
Sign = -1;
end
k = k + 2;
Cos_Estimate = Cos_Estimate + (x^k/(factorial(k)*Sign));
Errrr = abs(Cos_Estimate - cos(x));
end
err = abs(Cos_Estimate - cos(x));
fprintf('The estimated cosine value based on the Taylor Series is: %0.6f \n',Cos_Estimate)
fprintf('The actual cosine value is : %0.6f \n',cos(x))
fprintf('The estimation error is: %0.6f \n',err)
fprintf('The number of terms required was: \n',term)
Now I am getting NaN for my variable. I'm stuck.
채택된 답변
추가 답변 (2개)
Azzi Abdelmalek
2013년 3월 6일
편집: Azzi Abdelmalek
2013년 3월 6일
0 개 추천
Your code never enter in the loop because Errrr is not defined
댓글 수: 5
Derryn
2013년 3월 6일
Matt Kindig
2013년 3월 6일
편집: Matt Kindig
2013년 3월 6일
The issue is because the factorial() function, at very high values of k, exceeds the limit for double-precision numbers (specifically, you get a value of Inf). To demonstrate, run this at the command line:
>> factorial(160:180)
Notice that after the 11th column (i.e. factorial(170)) the factorial no longer is defined. When dividing by Inf, you get NaN in Cos_Estimate.
To fix this, the easiest way might be to add a second condition to your while loop, to terminate when k exceeds 170 or so.
Also, you don't define 'term' anywhere in your code, so the last line throws an error.
Matt Kindig
2013년 3월 6일
편집: Matt Kindig
2013년 3월 6일
Also, what exactly is the point of the "estimation error" calculation (calculation of 'err')? By definition, won't this be equal to Errrr, because you have defined it that way? Also, won't 'err' always be less than 0.000001, because of the way you have defined your loop?
Derryn
2013년 3월 6일
카테고리
도움말 센터 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!