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 Center および File ExchangeMathematics についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by