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.
댓글 수: 0
채택된 답변
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
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
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Eigenvalue Problems에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!