Divide and Average Method to Calculate Square Root
7 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hi, I am trying to write a function that uses the divide and average method to calculate a square root of both positive and negative numbers given a certain tolerance.
function estSqrt= ApproxSqrt(a,tol)
% function estSqrt= ApproxSqrt(a,tol)
if tol < 0
disp('Your tolerance cannot be less than zero');
return
end
if a < 0
b = abs(a);
else
b = a;
end
xOld= b/2;
%checkCon = true;
while 1==1 %run until the if statement breaks the loop
xNew = (xOld+a/xOld)/2;
error = (xOld-xNew)/(xOld);
xOld=xNew;
if error<tol %test to see if the error is within acceptable bounds
break %exit the while loop
end
end
if a < 0
estSqrt = xOld*1i;
return
end
estSqrt = xNew;
end
However, if I try to use negative numbers, the code enters an infinite loop and does not return a value. Also, it returns incorrect value if the tolerance is higher (ie ApproxSqrt(1000000,0.5) should return 1027.65111408149323 but it instead returns 250001. Any help figuring this out would be greatly appreciated! Thanks!
0 comentarios
Respuestas (1)
Steven Lord
el 11 de Feb. de 2019
A couple comments about your while loop:
while 1==1 %run until the if statement breaks the loop
There are better ways to end the loop. See comment below.
xNew = (xOld+a/xOld)/2;
You defined a variable b above the loop, but you're using a here. Should you be using b?
error = (xOld-xNew)/(xOld);
There is a function named error in MATLAB, so I recommend avoiding using that name. Perhaps relativeError would be better? Also, do you care about the sign of the error or just its magnitude?
xOld=xNew;
if error<tol %test to see if the error is within acceptable bounds
break %exit the while loop
end
Rather than tucking your loop termination condition deep inside the loop, why not specify it at the beginning? While the error is greater than the termination tolerance ...
end
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements 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!