While Loop for Percent Error Not Ending
1 次查看(过去 30 天)
显示 更早的评论
Hello! This is the first time i am posting a question so i apologize if i format it incorrectly.
I am trying to create a while loop that will determine how many iterations are needed for the percent error between the taylor series for sin and the matlab sin() function to be below 2%. The code i currently have just continues to run without an end in sight. Here's what i have:
x=sym('x')
x=input('Enter a scalar value for x.')
n=0:100000;
e=100000;
k=0;
while e>2
for i=1:length(n)
y(i)=((-1).^n(i))*((x.^(2*n(i))+1)/factorial((2*n(i))+1));
k=k+n(i);
u=sin(x);
e=((abs(u-k)/abs(k))*100);
%i=n(i);
end
end
fprintf('Percent Error:%d',e)
For reference i am using the generalized version of the Taylor series that is attached.
Thank you in advance!
0 个评论
采纳的回答
Mischa Kim
2016-8-5
Madi, how about
x = input('Enter a scalar value for x: ');
n = 0;
e = 3;
k = 0;
while e>2
dk = (-1)^n*x^(2*n + 1)/factorial(2*n + 1);
k = k + dk;
u = sin(x);
e = ((abs(u-k)/abs(k))*100);
n = n + 1;
fprintf('Terms: %d, percent error: %3.2d\n', n, e)
end
No need for the sym command. The entire computation is done numerically.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!