Divide and average method: while loop is overshooting approx. answer by one loop
12 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
Mario Malic
on 5 Sep 2020
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
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!