Taylor series using For loop to approximate Sin(x).
37 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2021-10-18
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!