# how to stop logical operators?

2 visualizzazioni (ultimi 30 giorni)
kakato il 25 Nov 2013
Commentato: kakato il 25 Nov 2013
I need to create a program that calculates square root of 2 using loop. starting with t=0.5. I need to stop cycle (and print iteration number i) when the t(i) is same for approximation : if abs((t(i)-t(i+1)))<10^-6. Can anyone help me? please please please :)
t(1)=0.5
for i=1:10
t(i+1)=1/2*(t(i)+2/t(i));
if abs((t(i)-t(i+1)))<10^-6
[ i, t(i)]
else
end
end
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposte (2)

Walter Roberson il 25 Nov 2013
if condition
break
end
##### 3 CommentiMostra 1 commento meno recenteNascondi 1 commento meno recente
Aviram Gelblum il 25 Nov 2013
t(1)=0.5;
t(2)=1/2*(t(1)+2/t(1));
i=1;
while abs((t(i)-t(i+1)))>=10^-6
t(i+2)=1/2*(t(i+1)+2/t(i+1));
i=i+1;
end
t=t(end-1);
kakato il 25 Nov 2013
Thanks a lot :)

Accedi per commentare.

Laurent il 25 Nov 2013
Modificato: Laurent il 25 Nov 2013
Instead of a for-loop, you can use a while loop. Something like this:
while abs((t(i)-t(i-1)))>10^-6
i=i+1;
end
##### 1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
kakato il 25 Nov 2013
thank u :)

Accedi per commentare.

### Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by