物理 简谐振动动画模拟python代码

chatgpt随手帮我写的
模拟简谐振动。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Set up the figure
fig = plt.figure(figsize=(5, 5))
ax = fig.add_subplot(111, aspect='equal', xlim=(-2, 2), ylim=(-1.5, 1.5))
# Create the balls
ball1 = plt.Circle((0, 0), radius=0.1, fc='blue')
ball2 = plt.Circle((0, 0), radius=0.1, fc='red')
# Add the balls to the plot
ax.add_patch(ball1)
ax.add_patch(ball2)
# Add a dashed line between the balls
line, = ax.plot([], [], 'k--')
# Add a dashed circle representing the trace of the uniform circular motion
circle = plt.Circle((0, 0), radius=1, fill=False, ls='--')
ax.add_patch(circle)
# Define the function to animate the balls and the line
def animate(i):
# Calculate the position of the first ball (uniform circular motion)
angle = i * 0.1 # Calculate the angle based on the frame number
x1 = np.cos(angle) # Calculate the x-coordinate of the ball
y1 = np.sin(angle) # Calculate the y-coordinate of the ball
ball1.center = (x1, y1) # Move the ball to the new position
# Calculate the position of the second ball (simple harmonic motion)
x2 = i *0.1 # Calculate the x-coordinate of the ball
y2 = np.sin(x2) # Calculate the y-coordinate of the ball
ball2.center = (x1, -1) # Move the ball to the new position
# Update the line connecting the two balls
line.set_data([x1, x1], [y1, -1])
# Create the animation
ani = animation.FuncAnimation(fig, animate, frames=360, interval=20)
# Show the plot
plt.show()
共0条回复
时间正序
回复是交流的起点,交流让学竞赛不孤单