Code Discrepancy Compared to Textbook

Joined
Dec 19, 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: 33
Joined
Dec 19, 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)
 
Joined
Jul 4, 2023
Messages
609
Reaction score
81
IMO, your code is identical to the code from the book, so it seems the book shows an incorrect result.
 
Joined
Sep 20, 2022
Messages
318
Reaction score
41
I do not understand your program (a few comments would be nice) but common sense is telling me that these 3 lines should have the same indentation.
Code:
if rdiff == 0:
elif rdiff == 1:
elif rdiff == -1:
 

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

No members online now.

Forum statistics

Threads
474,471
Messages
2,571,823
Members
48,797
Latest member
PeterSimpson
Top