0

I'm attempting to write a while loop iteration such that it stops when my value converges. When the new value is only 1% different from the last, I want the code to stop. Here is the iterative relationship:

Iteration

And here is my code thus far:

% Given values
clear all
clc
Tt4 = 3250
pi_c = 25
alpha = 0.5
M_0 = 1.6
h = 40 
T0 = 390.01
a_0 = 967.68
g_c = 1.4
g_t = 1.3
Cpc = 0.24
Cpt = 0.296
h_pr = 18400
M_6 = 0.4
pi_Mmax = 0.96
eta_m = 0.99
eta_b = 0.99
% From table 6.2
pi_dmax = 0.96
e_c = .9
e_f = .89
pi_b = 0.95
eta_b = 0.999
e_t = 0.89
pi_n = 0.97
eta_m = 0.995

% Calculations
R_c = ((g_c-1)/g_c)*Cpc
R_t = ((g_t-1)/g_t)*Cpt
V_0 = a_0*M_0
tao_r = 1+((g_c-1)/g_c)*M_0^2
pi_r = tao_r^(g_c/(g_c-1))
eta_r = 1-0.075*(M_0-1)^1.35
pi_d = pi_dmax*eta_r
tao_l = (Cpt*Tt4)/(Cpc*T0)
tao_c = pi_c^((g_c-1)/(g_c*e_c))
eta_c = (pi_c^((g_c-1)/g_c)-1)/(tao_c-1)
f = (tao_l-tao_r*tao_c)/((eta_b*h_pr)/(Cpc*T0)-tao_l)

% Iteration for tao_f
tao_f = (tao_r*(alpha-(tao_c-1))+eta_m*(1+f)*tao_l)/(tao_r*alpha + eta_m*              (1+f)*tao_l/((pi_c*pi_b).^((g_t-1)*e_t/g_t)))
tao_fi = (tao_r*(alpha-(tao_c-1))+eta_m*(1+f)*tao_l)/((tao_r*alpha + eta_m*(1+f)*tao_l/((pi_c*pi_b).^((g_t-1)*e_t/g_t)))*(tao_f).^(((g_c*(g_t- 1)*e_t*e_f)/g_t*(g_c-1))-1))

while abs((tao_f)-(tao_fi)) > .2
    tao_ff = (tao_r*(alpha-(tao_c-1))+eta_m*(1+f)*tao_l)/((tao_r*alpha + eta_m*(1+f)*tao_l/((pi_c*pi_b).^((g_t-1)*e_t/g_t)))*(tao_f).^(((g_c*(g_t-1)*e_t*e_f)/g_t*(g_c-1))-1))
end 

I new to matlab and coding in general, I know that my code is stuck in an infinite loop but I'm not sure why.

Any help is much appreciated!

Doug Fox
  • 23
  • 1
  • 1
  • 6
  • 6
    In your while loop you only change `tao_ff` (assigning new value every loop iteration). And every step you check the condition `abs((tao_f)-(tao_fi)) > .2`. As long as variables `tao_f` and `tao_fi` are not changing at all, your loop will never stop – Mikhail Genkin Mar 16 '15 at 19:09
  • 1
    If you are not sure, you can always add a counter – Buck Thorn Mar 16 '15 at 19:54
  • While it is true that the infinite loop is due to wrong comparators, it is always in general good to add a counter. In this case the algorithm may be stable, but in general there is no guarantee that the algorithm will actually converge. In that case it is good to make sure that the algorithm stops anyway and return a message, and/or value – patrik Mar 17 '15 at 11:58

0 Answers0