Implementing a while loop into my code?

2 次查看(过去 30 天)
I attached the script for my code. I want a whike loop that will calculate the estimate for the sine of the angle by adding one additional term from the Taylor Series polynomial (which is the Estimate= equation) each iteration through the loop. The while loop should continue as long as the absolute value of the difference between the most recent estimate and the previous estimate exceeds 0.00001 (1e-5). Is my code correct, Do i need to move my Error line up in the while loop, so it keeps running?

采纳的回答

Star Strider
Star Strider 2015-10-23
There were a few problems, the most significant being that you need to compare ‘Previous’ and Estimate in the while statement. Others were that you needed to initialise some variables before the loop, and iterate ‘k’:
%%Problem 3
Angle = input('Enter an angle in radians between 0 and 2pi: ');
Terms = input('Enter the desired number of terms for Taylor Series: ');
Estimate = 0; % Initialize Estimate
Previous = 10; % CHANGED: Initialise ‘Previous’
k = 1; % CHANGED: Initialise ‘k’
while abs(Estimate-Previous)>0.00001 % CHANGED: ‘abs’ Argument
Previous=Estimate;
Estimate = Estimate + (-1)^(k-1)*Angle^(2*k-1)/factorial(2*k-1);
k = k + 1; % CHANGED: Iterate ‘k’
% New value for Estimate = Old value for Estimate plus Next Term in
% Taylor Series
end
Error = abs(sin(Angle)-Estimate);
fprintf('The Taylor Series estimate for sin(Angle) is: %0.6f \n',Estimate);
fprintf('The actual value for sin(Angle) is: %0.6f \n',sin(Angle));
fprintf('The absolute error in the estimate is: %0.6f \n',Error);
It seems to work. I’ll let you troubleshoot it from here if there are still problems.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by