jeudi 19 avril 2018

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 question is: The steps of calculations is 101and 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.

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])




Aucun commentaire:

Enregistrer un commentaire