Nested loops to estimate cos(pi/4)
Show older comments
I have written this code that is giving me an error:
true = cos(pi/4);
n = 2;
es = .5^(2-n);
x = pi/4;
ea = 1;
est = 1;
k = 1;
while(1)
for ea >= es
est = 1+x^(k*2)/factorial(k*2)*(-1)^k
ea = abs(true-est)/true*100
end
k = k+1;
end
Clearly, I do not understand the relationship of for to while loops. Can anyone help me understand?
Thank you, Mary
Accepted Answer
More Answers (1)
Image Analyst
on 9 Dec 2016
You don't need both. You need just one of the other. the for loop is most straightforward in this case:
theta = pi;
trueValue = cos(theta);
numberOfTerms = 10; % Whatever.
theSum = 0;
for k = 0 : numberOfTerms-1
thisTerm = (-1)^k * theta ^ (2*k) / factorial(2*k);
theSum(k+2) = theSum(k+1) + thisTerm;
theError(k+1) = theSum(k+2) - trueValue;
end
% Make fancy plots.
subplot(2, 1, 1);
plot(theSum, 'b*-', 'LineWidth', 2);
ylabel('The Taylor Sum', 'FontSize', 20);
xlabel('Number of Terms', 'FontSize', 20);
grid on;
subplot(2, 1, 2);
plot(theError, 'b*-', 'LineWidth', 2);
ylabel('The Error from True Value', 'FontSize', 20);
xlabel('Number of Terms', 'FontSize', 20);
grid on;
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
% Get rid of tool bar and pulldown menus that are along top of figure.
set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')

1 Comment
Mary Jeppson
on 10 Dec 2016
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!