MATLAB Answers

need help for transfer Whlile loop from For loop

1 view (last 30 days)
pepper
pepper on 1 Oct 2020
Commented: Sindar on 1 Oct 2020
two newton method written with for and while loop.
the result is quite different
where should i fix it?
big thx from bottom of my heart.

  0 Comments

Sign in to comment.

Answers (1)

Sindar
Sindar on 1 Oct 2020
First issue:
  • for loop ends when error<tol
  • while loop continues when error<tol

  4 Comments

Show 1 older comment
Sindar
Sindar on 1 Oct 2020
can you comment your current code, in a comment block (not a screenshot)? But, similarly to the first issue, think about what is happening during the for/while loops, versus what happens before each loop - is it consistent?
pepper
pepper on 1 Oct 2020
function p1=newton(ex31,a)
tol=10^-10;
a=5;
p0=2;
for k=1:1000
p1=1/2*(p0+a/p0);
error=abs((p1-p0)/p0);
p0=p1;
if error<tol
p=p1;
break
end
end
-------------------------------------------------
i slightly changed value to pn and it run ok !
one thought in my mind is ,
is it possible that i make it run ok with the first one?(above one)
kinda lacked if i use p1,p0 value
function p1=newton(ex31,a)
tol=10^-4;
error=1.0;
p0=2;
pn=p0;
a=5
while error>tol
pn1=1/2*(pn+a/pn);
error=abs(pn1-pn)/abs(pn1-p0);
pn=pn1;
end
pn1
i don't understand about your consistent means.
Sindar
Sindar on 1 Oct 2020
switching between text and code blocks helps readability
"for"
function p1=newton(ex31,a)
tol=10^-10;
a=5;
p0=2;
for k=1:1000
p1=1/2*(p0+a/p0);
error=abs((p1-p0)/p0);
p0=p1;
if error<tol
p=p1;
break
end
end
"while"
function p1=newton(ex31,a)
tol=10^-4;
error=1.0;
p0=2;
pn=p0;
a=5
while error>tol
pn1=1/2*(pn+a/pn);
error=abs(pn1-pn)/abs(pn1-p0);
pn=pn1;
end
pn1
issues in both
  • regardless of what value is passed to the function, you set a=5
  • error is an important built-in function, use a different variable name
  • you have more p variables than necessary (you only need two)
differences between codes:
  • tol is not the same
  • "while" error is defined incorrectly
  • "while" returns a variable that is never defined (p1)
My comment on consistency referred to the fact that your original "while" screenshot wasn't doing anything in particular each loop.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!