Taylor series using For loop to approximate Sin(x).
37 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Humza Khan
le 17 Oct 2021
Modifié(e) : Humza Khan
le 18 Oct 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?
0 commentaires
Réponse acceptée
Walter Roberson
le 18 Oct 2021
SIN(-3)
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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!