Code Discrepancy Compared to Textbook

Joined
Dec 20, 2024
Messages
2
Reaction score
0
I am working on implementing the first example in a book but for some reason I am getting a different answer even though I did not change any of the code. Do you see what I may be doing wrong? From the book:
1734660874009.png

1734660891740.png

1734660919732.png

1734660963084.png

And my code:
1734660987979.png

1734661039355.png

The outputs, which should be the same, are highlighted in blue. What could I be doing wrong?
 

Attachments

  • 1734660937991.png
    1734660937991.png
    41.2 KB · Views: 4
Joined
Dec 20, 2024
Messages
2
Reaction score
0
Python:
import numpy as np
m = 3
m2 = m ** 2
q = np.zeros(m2)
q[m2 // 2] = 1
def get_P(m, p_up, p_down, p_left, p_right):
    m2 = m ** 2
    P = np.zeros((m2, m2))
    ix_map = {i + 1: (i // m, i % m) for i in range(m2)}
    for i in range(m2):
        for j in range(m2):
            r1, c1 = ix_map[i + 1]
            r2, c2 = ix_map[j + 1]
            rdiff = r1 - r2
            cdiff = c1 - c2
            if rdiff == 0:
                if cdiff == 1:
                    P[i, j] = p_left
                elif cdiff == -1:
                    P[i, j] = p_right
                elif cdiff == 0:
                    if r1 == 0:
                        P[i, j] += p_down
                    elif r1 == m - 1:
                        P[i, j] += p_up
                    if c1 == 0:
                        P[i, j] += p_left
                    elif c1 == m - 1:
                        P[i, j] += p_right
                elif rdiff == 1:
                    if cdiff == 0:
                        P[i, j] = p_down
                elif rdiff == -1:
                    if cdiff == 0:
                        P[i, j] = p_up
    return P
P = get_P(3, 0.2, 0.3, 0.25, 0.25)
n = 1
Pn = np.linalg.matrix_power(P, n)
np.matmul(q, Pn)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,073
Messages
2,570,538
Members
47,195
Latest member
RedaMahuri

Latest Threads

Top