What is the function of flag in this code?

1 回表示 (過去 30 日間)
Jimena Reyes Garces
Jimena Reyes Garces 2019 年 1 月 31 日
編集済み: Stephen23 2019 年 1 月 31 日
clear all;close all;clc;
es=0.05*10^-3;
sum=0;
i=0;
ea=1;
x=input('Enter x: ');
flag=1;
while(abs(ea)>es)
prev=sum;
sum=sum+flag*(x^i)/factorial(i);
i=i+2;
ea=(sum-prev)/sum;
flag=0-flag;
end
sum

採用された回答

Stephen23
Stephen23 2019 年 1 月 31 日
編集済み: Stephen23 2019 年 1 月 31 日
On each loop iteration the flag value changes sign, so it follows this pattern:
+1
-1
+1
-1
...
This has the effect of alternately adding or subtracting the following term:
+ (x^0)/factorial(0)
- (x^2)/factorial(2)
+ (x^4)/factorial(4)
- (x^6)/factorial(6)
...
This avoids the need to call two different plus and minus operators (but that would also be a perfectly viable approach).

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by