Why this algorithm produces a relative error?
Show older comments
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.
Accepted Answer
More Answers (1)
Image Analyst
on 30 Nov 2019
1 vote
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.
Categories
Find more on Performance and Memory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!