Search code examples
pythonfor-loopwhile-loopindentation

Probably wrong indentations in my loop, but where exactly?


I need to calculate the probability of how many rows out of 10000 rows of X met this condition: if abs(X[j,i])>10. Once it happend in a row, it doesn't matter to me how many times it happend in that row, only that it HAPPENED, so I used varaible d.
I probably have a problem of indentation because this is my output:

prob. for sigma= 0.1 is 1.0
prob. for sigma= 0.225 is 1.0
prob. for sigma= 0.35 is 1.0
prob. for sigma= 0.475 is 1.0
prob. for sigma= 0.6 is 1.0

My code:

import numpy as np 
import numpy.random as npr
j=0
T=10
M=10000
N=200
h=T/N
sigma=np.linspace(0.1,0.6,num=5)
X=np.ones(shape=(5*M,N)) 
X[:,0]=0.5  # X0=5
Z=npr.randn(5*M,N)    # normal random numbers
for S in range(1,6):
    s=sigma[S-1]
    while j<=S*M-1:
        for i in range(0,N-1): # Euler
            X[j,i+1]=X[j,i]+X[j,i]*(1-X[j,i])*h+s*Z[j,i]*np.sqrt(h)        
        j+=1  
D=[]
d=[]
for S in range(1,6):  **# here starts the problem**
    s=sigma[S-1]
    for j in range((S-1)*M,M*S):  
        for i in range(0,N):
            if abs(X[j,i])>10:
                D.append(X[j,i])
        d+=[len(D)]
        D=[]
    P=(len(d))/M
    print("prob. for sigma=",s, "is", P)
    d=[]

Solution

  • Your problem is that you're always appending len(D) to d, so len(d) is always equals to M.

    Change this part:

    D=[]
    d=[]
    for S in range(1,6):  **# here starts the problem**
        s=sigma[S-1]
        for j in range((S-1)*M,M*S):  
            for i in range(0,N):
                if abs(X[j,i])>10:
                    D.append(X[j,i])
            d+=[len(D)]
            D=[]
        P=(len(d))/M
        print("prob. for sigma=",s, "is", P)
        d=[]
    

    to this one:

    D=[]
    d=[]
    for S in range(1,6):  # here starts the problem
        s=sigma[S-1]
        for j in range((S-1)*M,M*S):  
            for i in range(0,N):
                if abs(X[j,i])>10:
                    D.append(X[j,i])
            if len(D) > 0:
                d.append(len(D))
            D=[]
        P=len(d)/M
        print("prob. for sigma=",s, "is", P)
        d=[]
    

    And you'll get this output:

    prob. for sigma= 0.1 is 0.0
    prob. for sigma= 0.225 is 0.0089
    prob. for sigma= 0.35 is 0.1174
    prob. for sigma= 0.475 is 0.3111
    prob. for sigma= 0.6 is 0.4879