# How to do iteration until certain tolerance is achieve?

2 views (last 30 days)
Abba Alhaji Bala on 30 Jul 2021
Commented: Abba Alhaji Bala on 31 Jul 2021
Hello! i wanted to iterate a function with an initial value to get a new value and then keep subtituting the new value back to the function, this process will continue until when the tolerance condition is achieved. i tried using "while loop" but it shows no iteration. No any new value obtained. please help me to check the code.
This is the equation: (psic/psit) + 1/(2*sigma) = 1
clear, clc;
psit=0.1; % initial
tol=1.0e-6;
sigma=0.8;
psic=-0.2079;
k=0; % iteration
while abs((psic/psit)+(1/(2*sigma)))<tol
psit=((psic/psit)+(1/(2*sigma)))-1
k=k+1;
end
disp(psit)

Walter Roberson on 30 Jul 2021
while abs((psic/psit)+(1/(2*sigma)))<tol
That tells us that you are looking for (psic/psit)+(1/(2*sigma)) to become as close to 0 as possible, which is the same as solving
psic/psit + 1/(2*sigma) == 0
psic + psit/(2*sigma) == 0*psit
psit/(2*sigma) == -psic
psit == -psic*2*sigma %solution
but...
psit=((psic/psit)+(1/(2*sigma)))-1
notice the -1 . That -1 tells us that you want to solve for psic/psit + 1/(2*sigma) == 1 instead of psic/psit + 1/(2*sigma) == 0
The contradiction between those leads the equation to loop endlessly (once you change the < tol to > tol )
Abba Alhaji Bala on 31 Jul 2021
yeah, that is right. thanks