使用while循环重复循环步骤以达到正确的答案 [英] Using while loop to repeat a step of loop to reach the proper answer
问题描述
我有以下代码,我只写了它的最后一部分。出于某些原因,我们使用 random.normal
值。很明显, func
函数有三个变量。
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.
我的问题是:计算的步骤是 101
,我们确切地说 100
输出中每个参数的值。我该怎么告诉Python,如果你看到 Wo [i]> 0
和 Omo [i]< 0
重新计算该步骤(将使用另一个随机数),直到我们得到正确答案(Wo [i]< 0和Omo [i]> 0
。
My question is: The steps of calculations is 101
and exactly we have 100
values for each parameter in output. How should I tell Python, If you see Wo[i]>0
and Omo[i]<0
recalculate that step (which would use another random number) until we have the proper answer (Wo[i]<0 and Omo[i]>0
.
我们必须这样做,因为,如果我们打印输出然后删除那些不符合我们条件的值,我们就有了,例如, 60个值而不是100个。我知道我们可以使用 while循环
但我不知道如何。
We have to do this because, If we print outputs and then remove those values which do not satisfy our condition, we have for example, 60 values instead of 100. I know we can use while loop
but I do not know how.
N=101
for i in range (1,N):
R=np.random.uniform(0,1)
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()
L = exp(-0.5 * ( func(Omn[i], Wn[i], Mn[i] ) - func( Omo[i-1], Wo[i-1], Mo[i-1] )))
if L>R:
Wo[i]=Wn[i]
Mo[i]=Mn[i]
Omo[i]=Omn[i]
else:
Wo[i]=Wo[i-1]
Mo[i]=Mo[i-1]
Omo[i]=Omo[i-1]
print(Wo[i],Mo[i],Omo[i])
推荐答案
插入,而
循环以重复您需要的计算。
Insert a while
loop to repeat the calculations you require.
当 L> R
, Wo
和 Omo
更新为 Omn
和 Wn
值。因此,如果此值为 Omn< 0
或 Wn> 0
,则需要重新计算它们。
当 L< = R
, Wo
和 Omo
是从上一次迭代计算出来的。由于上一次迭代已经 Wo [i]< = 0
而 Omo [i]> = 0
你不需要重复那些计算。
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.
因此,如下面的代码所示,您只需要重新计算Omn和Wn变量:
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 = 101
for i in range (1,N):
is_valid = False
if __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] >= 0 and 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])
这篇关于使用while循环重复循环步骤以达到正确的答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!