import numpy as np
import matplotlib.pyplot as plt
class QuantumRandomWalk:
def __init__(self, steps, num_positions):
self.steps = steps
self.num_positions = num_positions
self.position = np.zeros((2, steps + 1)) # Two rows for left and right directions
self.state_vector = np.array([[1], [0]]) # Initial state: superposition
def step(self):
# Generate quantum probabilities
probability_matrix = np.array([[0.5, 0.5], [0.5, 0.5]])
random_number = np.random.rand()
if random_number < 0.5:
self.state_vector = np.dot(probability_matrix, self.state_vector) # Superposition
else:
self.state_vector = np.dot(probability_matrix.T, self.state_vector)
# Update position based on the state vector
self.position[0, self.step_count + 1] = self.position[0, self.step_count] – 1 # Move left
self.position[1, self.step_count + 1] = self.position[1, self.step_count] + 1 # Move right
def run(self):
for self.step_count in range(self.steps):
self.step()
def visualize(self):
# Calculate probability distribution
prob_dist = np.zeros(self.num_positions)
for i in range(self.steps + 1):
left_pos = int(self.position[0, i]) + self.num_positions // 2
right_pos = int(self.position[1, i]) + self.num_positions // 2
prob_dist[left_pos] += abs(self.state_vector[0])**2
prob_dist[right_pos] += abs(self.state_vector[1])**2
plt.figure(figsize=(10, 6))
plt.title(“Quantum Random Walk Probability Distribution”)
plt.xlabel(“Position”)
plt.ylabel(“Probability”)
plt.bar(range(self.num_positions), prob_dist, color=’blue’, alpha=0.6)
plt.axvline(x=self.num_positions // 2, color=’r’, linestyle=’–‘)
plt.grid()
plt.show()
if __name__ == “__main__”:
steps = 1000
num_positions = 200
qr_walk = QuantumRandomWalk(steps, num_positions)
qr_walk.run()
qr_walk.visualize()