Divide and average method: while loop is overshooting approx. answer by one loop

조회 수: 12 (최근 30일)
CVIl
CVIl 2020년 9월 5일
답변: Mario Malic 2020년 9월 5일
If x=1, tol=10^4, and a=64, Matlab's final answer based on my code is equal to 8.05555. When I unsuppress the 'xi' equation in the code below, I can see that xi=8 was calculated but then one additional xi value was calculated. The additional value, 8.05555, was the final value presented in Matlab as the answer. This occurance is also the case for non-perfect squares, the answer presented as the answer is one loop over the most accurate answer. Why is this over step occurring?
Code:
function [xi,e] = Myfun2(x,tol,a)
xi=(0.5*(x+a/x));
if x>0 && a>0
while 1
x=x+1;
xi=(0.5*(x+a/x));
e=abs((x+1)-x/(x+1));
if x>xi
break
end
end
end
Command Window (when 'xi' unsuppressed in function):
>> Myfun2(1,10^4,64)
xi =
17
xi =
12.166666666666666
xi =
10
xi =
8.900000000000000
xi =
8.333333333333332
xi =
8.071428571428571
xi =
8
xi =
8.055555555555555
ans =
8.055555555555555

답변 (1개)

Mario Malic
Mario Malic 2020년 9월 5일
Your xi and e are calculated and then if x>xi condition is checked, it should be the other way around.
if x>0 && a>0
while 1
if x>xi
break
end
x=x+1;
xi=(0.5*(x+a/x));
e=abs((x+1)-x/(x+1));
end
end

카테고리

Help CenterFile Exchange에서 MATLAB Coder에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by