Taylor series using For loop to approximate Sin(x).

22 visualizaciones (últimos 30 días)
Humza Khan
Humza Khan el 17 de Oct. de 2021
Editada: Humza Khan el 18 de Oct. de 2021
function y = SIN(x)
%SIN This function takes the value and processes the approximate sin
%value of that input
% The value of sin is approximately calculated using Taylor Series
% from the input value x.
Sum = 0;
T = 1E-12; %defining tolerance.
for n = 0:29
an = ((-1)^n)*((x^((2*n)+1))/factorial((2*n)+1));
Sum = Sum + an;
if abs(an) < T || n==29
break
elseif abs(an) == T
disp 'More Iterations are needed to reach the specified tolerance.';
end
end
y = Sum;
end
the answer i am getting for lets say SIN(-3) = 4.500
however, the expected answer from using the built-in function sin(-3) = -0.1411.
how can i get the expected answer? I am very confused. THIS HAS TO BE DONE USING FOR LOOPS. How can i fix this code?

Respuesta aceptada

Walter Roberson
Walter Roberson el 18 de Oct. de 2021
SIN(-3)
More Iterations are needed to reach the specified tolerance. More Iterations are needed to reach the specified tolerance. More Iterations are needed to reach the specified tolerance. More Iterations are needed to reach the specified tolerance. More Iterations are needed to reach the specified tolerance. More Iterations are needed to reach the specified tolerance. More Iterations are needed to reach the specified tolerance. More Iterations are needed to reach the specified tolerance. More Iterations are needed to reach the specified tolerance. More Iterations are needed to reach the specified tolerance. More Iterations are needed to reach the specified tolerance. More Iterations are needed to reach the specified tolerance.
ans = -0.1411
function y = SIN(x)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
n = 0; Sum = 0; an=1;
T = 1E-12; %defining tolerance.
for n = 0:30
an = ((-1)^n)*((x^((2*n)+1))/factorial((2*n)+1));
Sum = Sum + an;
if abs(an) < T || n==30
break
else
disp 'More Iterations are needed to reach the specified tolerance.'
end
end
y = Sum;
end
You had the wrong starting point for n, and you had the wrong test for breaking.

Más respuestas (0)

Categorías

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

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by