1

Question:

I have a 3*3 transition matrix and another 3*1 matrix. On multiplying these two, I get another 3*1 matrix. I must multiply the new 3*1 matrix with the original 3*3 matrix and this will give me another 3*1 matrix. This has to continue until the 3*1 matrices attained in consecutive steps are close enough or if 10000 such multiplications are completed ( whichever comes first). To see if they are close enough, I have a function :

np.allclose(previous_x, new_x) # to determine if this process must continue or stop.

previous_x denotes the previous 3*1 matrix and new_x denotes the new 3*1 matrix at hand.

max_steps = 10000

The 'res' in the code below will sure turn 'True' at some point before the 10k steps run out in order to go into the else loop.but for some reason, its not happening. can you please help me solve this ?

[code]

def random_walk(P,x_0,max_steps = 10000):


    n_steps = 0

    def matrix_mult(P,x_0,n_steps):
        x = np.dot(P,x_0)
        res = np.allclose(x_0,x)
        n_steps = n_steps+1
        return x,res,n_steps

    x,res,n_steps = matrix_mult(P,x_0,n_steps)
    print(res)
    for i in range(max_steps-1):
        if(res==False):
            print('h')
            x_0 = x
            x=np.dot(P,x_0)
        else:
            print('g')
            x_0 = x
            x,res,n_steps = matrix_mult(P,x_0,n_steps)
            n_steps =i






    return x, n_steps
random_walk(np.array([[0,1,0.5],[1,0,0],[0,0,0.5]]),np.array([1,0,0]),max_steps = 10000)
VishwaV
  • 167
  • 12

2 Answers2

0

Your multiplication

P= np.array([[0,1,0.5],[1,0,0],[0,0,0.5]])
x_0= np.array([1,0,0])
x= np.dot(P,x_0)

yields:

np.array([0., 1., 0.])

So np.allclose(x, x_0) will return False and the else branch is never executed, because the only places in which res could be changed are before the loop and in the else branch (which is only reachable if the function call before the loop evalutes to res== True.

Btw: try to avoid comparing booleans using == True/False. Rather use is True/False. If you want to read more about this, please read this post.

jottbe
  • 4,228
  • 1
  • 15
  • 31
0

I think jottbe's answer alludes to it, but it could be more explicit:

Your code gets stuck in the first branch of your if/else because once it gets in, it never recomputes res. So if res is ever False it will always remain False (and you'll keep taking the first branch) until you hit the loop limit.

To solve the problem you probably need to be recomputing res each iteration of the loop. I don't really understand what you're doing with your separate matrix_mult function, but maybe you need to be calling every time. The if you probably need to do is more like if res: break to quit the loop early if you found that the multiplication isn't changing anything significantly. Everything else should happen on every iteration unconditionally.

Blckknght
  • 100,903
  • 11
  • 120
  • 169