Why this algorithm produces a relative error?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Eli
el 30 de Nov. de 2019
Comentada: Image Analyst
el 10 de Dic. de 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.
0 comentarios
Respuesta aceptada
Steven Lord
el 30 de Nov. de 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 comentarios
Image Analyst
el 10 de Dic. de 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.
Más respuestas (1)
Image Analyst
el 30 de Nov. de 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.
0 comentarios
Ver también
Categorías
Más información sobre Eigenvalue Problems en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!