Cos Taylor Series script rounds for 4 decimal places but changing to 5 causes it to loop infinitely
이전 댓글 표시
I have to write a script to count the nth number of terms it takes to get a 4 decimal match in cos(x) and the taylor series expansion of cos(x). I am using a while loop and round function to do this, and when i have the round set to 4 decimal places, the script runs as expected, but when I change it to 5 decimal places, it seems to run infinitely. I am also not using the built in factorial function, as the professor took points off for using it in a previous assignmet, so that is what the nested for loop is doing, running the factorial, which may be part of the issue
clear, clc
cts = 1; % Initial sum of cos taylor series, and also first term
x = pi/7;
f= 1;
ii = 1;
while round(cts,4) ~= round(cos(x),4)
ii = ii * 2;
for jj = 1:ii
f = f * jj;
end
nth_term = ( (-1)^(ii / 2) ) * ( (x^(ii) ) / (f));
cts = cts + nth_term;
f = 1;
end
terms = (ii / 2) + 1; % Number of terms (including the first '1' term to
% reach 4 decimal agreement
disp(round(cts,4));
disp(round(cos(x),4));
fprintf('The number of terms needed to reach 4 decimal place is %g.\n', terms)
This returns the expected answers of 0.9010 for both cts and cos(x) and prints 3 terms, but when I change round(..., 4) to round(...,5), it runs the while loop infinitely. Any help would greatly appreciated as to why this happens.
댓글 수: 4
Walter Roberson
2022년 11월 9일
for jj = 1:ii
f = f * jj;
end
Have you considered using factorial() ?
Spencer
2022년 11월 9일
"’m also curious as to why 4 decimal places works, but 5 doesn’t though."
Possibly because ROUND is not a robust approach:
The standard robust approach is to compare the absolute difference against a tolerance:
abs(A-B)<tol
Moksh
2023년 8월 28일
Hi Spencer,
You can try using the standard tolerance method and try printing the values for 'cts' and 'cos(x)', to get your required stopping criteria.
Sample code for this:
%% Try using different values for tolerance until the required results
while abs(cts - cos(x)) > tol:
%% Your logic
end
Hope this helps!
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Programming에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!