Filter löschen
Filter löschen

Why this algorithm produces a relative error?

2 Ansichten (letzte 30 Tage)
Eli
Eli am 30 Nov. 2019
Kommentiert: Image Analyst am 10 Dez. 2019
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.

Akzeptierte Antwort

Steven Lord
Steven Lord am 30 Nov. 2019
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 Kommentare
Eli
Eli am 9 Dez. 2019
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 am 10 Dez. 2019
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Image Analyst
Image Analyst am 30 Nov. 2019
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