vendredi 12 juillet 2019

Unable to increment integers as expected

I am following a short youtube video tutorial on Monte Carlo problems with python (https://www.youtube.com/watch?v=BfS2H1y6tzQ) and the code isn't working. The goal is to see how many times I will have to take transport to get back home, considering you take transport if the distance is greater than 4.

So I assumed the issue was that every time random_walk was called, the x,y variables are being reset to zero so the distance is never always within a 0-1 range and isn't incrementing as expected.

import random

def random_walk(n): x, y = 0, 0 for i in range(n): (dx, dy) = random.choice([(0, 1), (0, -1), (1, 0), (-1, 0)]) x += dx y += dy return (x, y)

number_of_walks = 10000 no_transport = 0

for walk_length in range(1, 31): for i in range(number_of_walks): (x, y) = random_walk(walk_length) distance = abs(x) + abs(y)

    if distance <= 4:
        no_transport += 1

transported_percentage = float(no_transport) / number_of_walks
print("Walk Size = ", walk_length, " / % transported = ", 100 * transported_percentage)

I expect results to show what % of the times I transported did I have to take transport home, instead, I get inaccurate numbers like 100,200,300%. Could the video tutorial have incorrect code?

Aucun commentaire:

Enregistrer un commentaire