フィルターのクリア

how to use a while loop to perform an infinite series approximation

3 ビュー (過去 30 日間)
Joe
Joe 2012 年 7 月 2 日
コメント済み: steven mcquade 2016 年 11 月 1 日
So I have to write a program using a while loop that uses the alternating series approximation for sin(x) using a while loop and compare it to the matlab sin(x) using an error function. so far I have:
clc
clear
x=input('Enter the value of x to compute sin(x): ');
error=1;
n=0;
while error >= 1*(10^-5);
terms = ((-1)^n)*(((x^(n+1)))/factorial(n+1));
SINx=sum(terms);
n=n+1;
error=abs((sin(x)-SINx)/sin(x))*100;
end
And my loop does nothing. Any ideas?

採用された回答

Tom
Tom 2012 年 7 月 2 日
編集済み: Tom 2012 年 7 月 2 日
Here's a shabby way of doing it...
x=pi/2; %test: sin(pi/2)=1;
error=1;
n=1;
count=0;
while error >= 1*(10^-3);
%x -x^3/3! +x^5/5! ...
count=count+1;
terms(count)=(-1)^(count+1)*(x^n)/factorial(n);
SINx=sum(terms);
n=n+2;
error=abs((sin(x)-SINx)/sin(x))*100;
end
disp(SINx)
  1 件のコメント
Joe
Joe 2012 年 7 月 2 日
that helped immensely thank you!

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2012 年 7 月 2 日
You are only generating a single value in "terms", and the sum() is being applied to that single value. You are not accumulating the values from the terms with n=0, n=1, n=2, etc..
  2 件のコメント
Tom
Tom 2012 年 7 月 2 日
That is true; also I think the series is incorrect- sine is something like this:x -x^3/3! +x^5/5! ...
Joe
Joe 2012 年 7 月 2 日
yes I see the error in the series -- I have to fix where the N starts counting for it to be right -- but how do I accumulate the n terms? do I need the while loop to be embedded in a For loop or vice versa?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCalculus についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by