Trying to calculate the square root of a positive number based on the “divide and average” scheme.
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
NikePro
am 21 Feb. 2016
Kommentiert: Roger Stafford
am 21 Feb. 2016
I am re-posting this as it would not post correctly earlier.
I am trying to calculate the square root of a positive number, a, based on the “divide and average” scheme. The scheme is formulated in the following:
x = ( x + a/x) / 2
My function, however, returns incorrect results. I was hoping someone could help me debug it.
function v = my_sqrtD(t)
%find the square root of t, and t must be larger than 0.
v_pre = t/2.0;
my_eps = 0.0001;
%when the limit is reached, stop the loop
n_limit = 1000000;
for i=1:n_limit
v = (v_pre + t/v_pre)/2.0;
res = abs((v-v_pre)/v);
if res < my_eps, break, end
end %end of loop
if (i==n_limit)
disp('The root cannot be found.');
end
0 Kommentare
Akzeptierte Antwort
Roger Stafford
am 21 Feb. 2016
Bearbeitet: Roger Stafford
am 21 Feb. 2016
The line
v = (v_pre + t/v_pre)/2.0;
is your trouble. It should read:
v_pre = (v_pre + t/v_pre)/2.0;
However, you will have to appropriately revise your computation of 'res'.
2 Kommentare
Roger Stafford
am 21 Feb. 2016
I've changed it a bit:
for i=1:n_limit
v = (v_pre + t/v_pre)/2.0;
res = abs((v-v_pre)/v);
v_pre = v; % <-- Update v_pre (That's what was missing)
if res < my_eps, break, end
...
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!