Why this algorithm produces a relative error?

3 ビュー (過去 30 日間)
Eli 2019 年 11 月 30 日
Commented: Image Analyst 2019 年 12 月 10 日
sum1=single(0); .
k=0;
sum=single(1);
while(sum==sum1)
sum=sum1;
k=k+1;
sum1=sum+single(1/k^2);
end
disp('expected result');
disp(pi^2/6); %1.6449
disp(somma); %1
disp('k:');
disp(k) %0
disp('RELATIVE ERROR: ');
disp(abs(somma-pi^2/6)/ (pi^2/6)); %0.3921
We works in finite arithmetic but I don't don't know the 'inner reason' of why this algorithm is so unstable. Thank you all.

0 件のコメント

サインイン to comment.

採用された回答

Steven Lord 2019 年 11 月 30 日
Walk through your code, line by line. How many times does MATLAB execute the body of your while loop?
I think you want to iterate while the two variables are not equal, breaking out of the loop when they are equal.
You also never define the variable somma that you display on the line with the %1 comment.
Image Analyst's point about your variable names is a good one. If you want to clearly indicate that they are your candidate sums, perhaps use variable names like sumPrevious and sumCurrent.

2 件のコメント

Eli 2019 年 12 月 9 日
Thank you so much! I changed the name of the variable, code works but i still don't understand why it produces relative error.
Image Analyst 2019 年 12 月 10 日
It produces the relative error because these lines are in your script:
disp('RELATIVE ERROR: ');
disp(abs(somma-pi^2/6)/ (pi^2/6)); %0.3921
Why would you expect it NOT to??? If you don't want it to, then delete those lines.

サインイン to comment.

Image Analyst 2019 年 11 月 30 日
Don't use sum as the name of your variable. It's the name of a built-in function that you don't want to destroy.

0 件のコメント

サインイン to comment.

サインイン してこの質問に回答します。

Translated by