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

22 Ansichten (letzte 30 Tage)
Humza Khan
Humza Khan am 17 Okt. 2021
Bearbeitet: Humza Khan am 18 Okt. 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?

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 18 Okt. 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.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by