While Loop for Percent Error Not Ending

조회 수: 1 (최근 30일)
Madi  Macias
Madi Macias 2016년 8월 5일
댓글: Madi Macias 2016년 8월 5일
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!

채택된 답변

Mischa Kim
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.
  댓글 수: 1
Madi  Macias
Madi Macias 2016년 8월 5일
Oh wow, that makes so much more sense. Thank you very much!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by