Why this algorithm produces a relative error?

2 次查看(过去 30 天)
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('your result:');
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.

采纳的回答

Steven Lord
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
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
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.

请先登录,再进行评论。

更多回答(1 个)

Image Analyst
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.

Community Treasure Hunt

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

Start Hunting!

Translated by