Using While Loop To Repeat A Step Of Loop To Reach The Proper Answer
I have the following code which I just write the final part of it. For some reasons we use random.normal values. As it is obvious the func function has three variables. My questio
Solution 1:
You can use a normal while loop and check the condition after calculating, for example:
for i in range (1,N):
R=np.random.uniform(0,1)
while True:
Omn[i] = Omo[i-1] + 0.05 * np.random.normal()
Wn[i] = Wo[i-1] + 0.05 * np.random.normal()
Mn[i] = Mo[i-1] + 0.1 * np.random.normal()
if Wo[i] <= 0and Omo[i] >= 0:
break
# rest of code
Solution 2:
Insert a while
loop to repeat the calculations you require.
When L > R
, Wo
and Omo
are updated with the Omn
and Wn
values. So if this values are Omn<0
or Wn>0
you need to re-calulate them.
When L <= R
, Wo
and Omo
are calculated from the previous iteration. Since the previous iteration already is Wo[i]<=0
and Omo[i]>=0
you don't need to repeat those calculations.
Thus, as shown in the code below, you only need to re-calculate the Omn and Wn variables:
Omo[0] = 0.24
Wo[0] = -0.2
Mo[0] = 1.0
N = 101for i inrange (1,N):
is_valid = Falseif__debug__:
print"Calculating position " + str(i)
while (not is_valid):
Omn[i] = Omo[i-1] + 0.05 * np.random.normal()
Wn[i] = Wo[i-1] + 0.05 * np.random.normal()
Mn[i] = Mo[i-1] + 0.1 * np.random.normal()
if__debug__:
print"- is_valid iteration values: " + str(Wn[i]) + " " + str(Omn[i])
print"- is_valid previous values: " + str(Wo[i-1]) + " " + str(Omo[i-1])
is_valid = Omn[i] >= 0and Wn[i] <= 0
R = np.random.uniform(0,1)
L = exp(-0.5 * ( func(Omn[i], Wn[i], Mn[i] ) - func( Omo[i-1], Wo[i-1], Mo[i-1] )))
if L > R:
Omo[i] = Omn[i]
Wo[i] = Wn[i]
Mo[i] = Mn[i]
else:
Omo[i] = Omo[i-1]
Wo[i] = Wo[i-1]
Mo[i] = Mo[i-1]
print(Wo[i], Mo[i], Omo[i])
Post a Comment for "Using While Loop To Repeat A Step Of Loop To Reach The Proper Answer"