Tuesday, 23 January 2024

Biased Random Walk

import random
from matplotlib import pyplot as plt
import numpy as np

def take_step(x, y, direction=(0,0), bias=0):
    probability = 0.5 + bias
    dx_choices = [-1, 1]
    dy_choices = [-1, 1]

    # Probability for moving in the preferred direction
    if direction[0] == 1:
        dx_prob = [1 - probability, probability]
    else:
        dx_prob = [probability, 1 - probability]

    if direction[1] == 1:
        dy_prob = [1 - probability, probability]
    else:
        dy_prob = [probability, 1 - probability]

    dx = random.choices(dx_choices, dx_prob)[0]
    dy = random.choices(dy_choices, dy_prob)[0]

    return x + dx, y + dy

history_x = [0]
history_y = [0]

# Example direction (1, -1) and probability 0.6
direction = (1, 1)  # Goal 
bias = 0.01 # 1-bias = luck

for step in range(50000):
    x, y = take_step(history_x[-1], history_y[-1], direction, bias)
    history_x.append(x)
    history_y.append(y)


# direction = (1, -1) 
# for step in range(50000):
#     x, y = take_step(history_x[-1], history_y[-1], direction, bias)
#     history_x.append(x)
#     history_y.append(y)
#
#
# direction = (-1, -1) 
# for step in range(50000):
#     x, y = take_step(history_x[-1], history_y[-1], direction, bias)
#     history_x.append(x)
#     history_y.append(y)



history_x = np.array(history_x)
history_y = np.array(history_y)

distances_to_origin = np.sqrt(history_x**2 + history_y**2)

print('Mean distance to origin:', np.mean(distances_to_origin))
print('Max distance to origin:', np.max(distances_to_origin))

plt.scatter(history_x, history_y, alpha=0.1, color='green')
# remove axes
plt.xticks([])
plt.yticks([])
plt.show()

No comments:

Post a Comment

Parse Wikipedia dump

""" This module processes Wikipedia dump files by extracting individual articles and parsing them into a structured format, ...