np.random.seed(0)
def random_drive(num_stops=10):
town = np.random.choice(G.nodes)
for _ in range(num_stops):
town = np.random.choice(G[town])
return town
destination = random_drive()
print(f"After driving randomly, the car has reached Town {destination}.")
After driving randomly, the car has reached Town 24.
使用 20,000 辆汽车模拟交通
import time
np.random.seed(0)
car_counts = np.zeros(len(G.nodes))
num_cars = 20000
start_time = time.time()
for _ in range(num_cars):
destination = random_drive()
car_counts[destination] += 1
central_town = car_counts.argmax()
traffic = car_counts[central_town]
running_time = time.time() - start_time
print(f"We ran a {running_time:.2f} second simulation.")
print(f"Town {central_town} has the most traffic.")
print(f"There are {traffic:.0f} cars in that town.")
We ran a 3.47 second simulation.
Town 12 has the most traffic.
There are 1015 cars in that town.
检查 3 号镇的交通情况
print(f"There are {car_counts[3]:.0f} cars in Town 3.")
There are 934 cars in Town 3.
将客流量计数转换为概率
probabilities = car_counts / num_cars
for i in [12, 3]:
prob = probabilities[i]
print(f"The probability of winding up in Town {i} is {prob:.3f}.")
The probability of winding up in Town 12 is 0.051.
The probability of winding up in Town 3 is 0.047.