import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# Parameters for the random polynomial
num_frames = 100  # Number of frames for the animation

# Function to compute zeros of a random polynomial
def compute_zeros(n):
    coefficients = np.random.normal(0, 1, n + 1)  # i.i.d. Gaussian coefficients
    roots = np.roots(coefficients[::-1])  # Roots of the polynomial
    return roots

# Initialize the figure and axis
fig, ax = plt.subplots(figsize=(6, 6))
ax.set_xlim(-1.5, 1.5)
ax.set_ylim(-1.5, 1.5)
ax.set_aspect('equal')
ax.set_title("Zeros of Random Polynomials")
ax.set_xlabel("Re")
ax.set_ylabel("Im")
circle = plt.Circle((0, 0), 1, color='blue', fill=False, linewidth=3, linestyle='--', label='Unit Circle')
ax.add_artist(circle)

# Scatter plot for zeros
scatter, = ax.plot([], [], 'ro', label='Zeros')

# Animation update function
def update(frame):
    zeros = compute_zeros(frame)
    scatter.set_data(zeros.real, zeros.imag)
    ax.set_title(f"Degree {frame}")
    return scatter,

# Create the animation
ani = FuncAnimation(fig, update, frames=num_frames, interval=200, blit=False)

# Add legend and show the animation
# ax.legend(loc='upper right')

if True:
    ani.save('hammersley-random-polynomial.mp4', writer='ffmpeg', fps=5)

plt.show()
