Taylor series using For loop to approximate Sin(x).
37 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Walter Roberson
on 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.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!