本文主要使用Python和Matplotlib制作动画,动态演示初中数学中的PQ沿矩形运动过M点的问题。
本文使用的软件:
- Python 3.8.8
- Matplotlib 3.3.4
- PyCharm 2018.3.3(Community Edition)
1 题目
矩形OABC的顶点B的坐标为(8,7),动点P从原点O出发,以每秒2个位的速度沿折线OA-OB运动,到B点时停止。同时,动点Q从点C出发,以每秒1个单位的速度在线段CO上运动,当一个点停止时,另一个点也随之停止。在运动过程中,当线段PQ恰好经过点M(3,2)时,运动时间t的值是多少?
2 动画源代码
import numpy as np
import matplotlib.animation as animation
import matplotlib.pyplot as plt
points = {'O': (0, 0),
'A': (0, 7),
'B': (8, 7),
'C': (8, 0),
'M': (3, 2)}
xdata, ydata = [], []
time_Q = 8 / 1
time_P = (8 + 7) / 2
time_move = time_Q if time_Q < time_P else time_P
frame_move = np.arange(0, time_move + 0.01, 0.05)
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 6))
plt.rc('font', family='Times New Roman', size=9)
plt.title('PQ沿矩形运动过M点', fontfamily='SimHei')
dot_P, = ax.plot([], [], 'yo')
dot_Q, = ax.plot([], [], 'bo')
line_PQ, = ax.plot([], [], 'r-')
text_P = ax.text(points['A'][0]-1, points['A'][1], 'P')
text_Q = ax.text(points['C'][0], points['C'][1]-1, 'Q')
def init_graph():
print('init frame')
ax.text(0, 8,
'''
矩形OABC的顶点B的坐标为(8,7),动点P从原点O
出发,以每秒2个位的速度沿折线OA-OB运动,到B点
时停止。同时,动点Q从点C出发,以每秒1个单位的
速度在线段CO上运动,当一个点停止时,另一个点
也随之停止。在运动过程中,当线段PQ恰好经过点
M(3,2)时,运动时间t的值是多少?(@猴小萌)''', fontfamily='FangSong', fontsize=10)
# Point O,A,B,C
ax.plot([points['O'][0], points['A'][0]], [points['O'][1], points['A'][1]], 'g-') # AB
ax.plot([points['A'][0], points['B'][0]], [points['A'][1], points['B'][1]], 'g-') # AB
ax.plot([points['B'][0], points['C'][0]], [points['B'][1], points['C'][1]], 'g-') # BC
ax.plot([points['C'][0], points['O'][0]], [points['C'][1], points['O'][1]], 'g-') # CO
# Text O,A,B,C
ax.text(points['O'][0]-0.5, points['O'][1], 'O')
ax.text(points['A'][0]-0.5, points['A'][1], 'A')
ax.text(points['B'][0]+0.2, points['B'][1], 'B (8,7)')
ax.text(points['C'][0]+0.2, points['C'][1], 'C')
# Point M
ax.plot(points['M'][0], points['M'][1], 'c*')
ax.text(points['M'][0]+0.2, points['M'][1], 'M (3,2)')
ax.set_xlim(-2, 10)
ax.set_ylim(-2, 12)
def animate(t):
# print(t)
# update P
if t < 7/2:
x_P = 0
y_P = t * 2
else:
x_P = t * 2 - 7
y_P = 7
dot_P.set_data(x_P, y_P)
text_P.set_position((x_P + 0.1, y_P + 0.2))
text_P.set_text('P ({:.1f}, {:.1f})'.format(x_P, y_P))
# update Q
x_Q = points['C'][0] - t * 1
y_Q = 0
dot_Q.set_data(x_Q, y_Q)
text_Q.set_position((x_Q, y_Q - 0.6))
text_Q.set_text('Q ({:.1f}, {:.1f})'.format(x_Q, y_Q))
# update PQ
line_PQ.set_data([x_P, x_Q], [y_P, y_Q]) # PQ
#return dot_P, dot_Q, text_P, text_Q, line_PQ
ani = animation.FuncAnimation(fig, animate, frames=frame_move, init_func=init_graph, interval=200, repeat=False)
ani.save('PQ沿矩形运动过M点.gif')
plt.show()