物理 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))
l = 2 # the length
# Create the balls
ball1 = plt.Circle((0, 0), radius=0.1, fc='blue')
ball2 = plt.Circle((0, +l/2), radius=0.02, 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')
# 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
# Calculate the x-coordinate of the ball
ang = 0.25*np.sin(angle) # Calculate the y-coordinate of the ball
ball1.center = (l*np.sin(ang),-l/2+l*(1-np.cos(ang)) )
# Update the line connecting the two balls
line.set_data([0, l*np.sin(ang)], [+l/2, -l/2+l*(1-np.cos(ang))])
# Create the animation
ani = animation.FuncAnimation(fig, animate, frames=360, interval=20)
# Show the plot
plt.show()
模拟出来是一个单摆。
共0条回复
时间正序
回复是交流的起点,交流让学竞赛不孤单