Borrar filtros
Borrar filtros

Implementing a while loop into my code?

2 visualizaciones (últimos 30 días)
Tyler Silva
Tyler Silva el 23 de Oct. de 2015
Respondida: Star Strider el 23 de Oct. de 2015
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?

Respuesta aceptada

Star Strider
Star Strider el 23 de Oct. de 2015
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.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by