import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib import rc
# Set up animation to render as interactive JavaScript in the blog
rc('animation', html='jshtml')
def run_stick_simulation(total_frames=60):
fig, ax = plt.subplots(figsize=(6, 6))
ax.set_aspect('equal')
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_xlabel("Length of piece 1 (x)")
ax.set_ylabel("Length of piece 2 (y)")
# Initialize point objects
sample_points, = ax.plot([], [], 'o', color='blue', markersize=0.8, alpha=0.6, label='Sample Space')
favorable_points, = ax.plot([], [], 'o', color='red', markersize=0.8, label='Favorable Outcomes')
ax.legend(loc='upper right')
x_s, y_s = [], []
x_f, y_f = [], []
def update(frame):
# Exponentially increase points per frame for a smooth visual 'reveal'
points_to_add = int(15 * (1.12**frame))
new_x = np.random.uniform(0, 1, points_to_add)
new_y = np.random.uniform(0, 1, points_to_add)
for x, y in zip(new_x, new_y):
z = 1 - (x + y)
if z > 0: # Inside the sample space
x_s.append(x)
y_s.append(y)
# Check triangle inequality
if (x + y > z) and (y + z > x) and (z + x > y):
x_f.append(x)
y_f.append(y)
sample_points.set_data(x_s, y_s)
favorable_points.set_data(x_f, y_f)
if len(x_s) > 0:
prob = len(x_f) / len(x_s)
ax.set_title(f"Simulations: {len(x_s)} | Probability: {prob:.4f}")
return sample_points, favorable_points
ani = FuncAnimation(fig, update, frames=total_frames, interval=50, blit=True)
plt.close() # Prevents extra static plot from showing
return ani
run_stick_simulation()