Python:对自由落体动画进行动画处理(动画问题)

时间:2019-03-16 10:00:04

标签: python animation

我受命使用python进行自由落体运动。

该项目即将结束,但是动画部分存在问题。动画不流畅。

基本上,每次弹出该图时,我都必须关闭它。打开->关闭->打开->继续

我不要那个。我想要这样:

The Animation I want

代码如下:

import numpy as np
import matplotlib.pyplot as plt

# initialization
x = 0                                   # initial x position
y = 0                                   # initial y position
v0 = int(input("v0 = "))                # initial velocity
angle = int(input("Angle = "))          # initial angle
angle_rad = (angle/360) * (2 * np.pi)   # convert degree to radian
g = -9.8                                # gravity
t = 0                                   # time
dt = 0.01                               # time step

# initialization array
x_arr = [x]
y_arr = [y]
t_arr = [t]

# velocity for x and y axis
vx = v0 * np.cos(angle_rad)
vy = v0 * np.sin(angle_rad)

# Update
while y >= 0:
    vy += g*dt
    y += vy*dt
    x += vx*dt
    t += dt
    if y < 0:
        break
    # store
    x_arr.append(x)
    y_arr.append(y)
    t_arr.append(t)

# Numeric
# Total Time
t_tot_num = t_arr[-1]

# Range
range_num = x_arr[-1]

# Max Height
h_max_num = np.max(y_arr)

# Analytic
x_ex_arr = [0]
y_ex_arr = [0]
for t in t_arr:
    x_ex = v0 * np.cos(angle_rad) * t
    y_ex = (0.5 * g * t**2) + (v0 * np.sin(angle_rad) * t)
    x_ex_arr = [x_ex]
    y_ex_arr = [y_ex]

# Total Time
t_tot_ex = (2 * v0 * np.sin(angle_rad)) / -g

# Range
range_ex = v0 * np.cos(angle_rad) * t_tot_ex

# Max Height
h_max_ex = (v0**2 * np.sin(angle_rad)**2) / (-2 * g)

plt.figure()
plt.plot(x_arr, y_arr, c='b', label='Numerik')
plt.plot(x_ex_arr, y_ex_arr, c='r', label='Analisis')
plt.axhline(c='black')
plt.axvline(c='black')
plt.legend()
plt.show()

# Compare
print("Numerik vs Analitik")
print("Total Time (s): %.2f vs %.2f" % (t_tot_num, t_tot_ex))
print("Range (m): %.2f vs %.2f" % (range_num, range_ex))
print("Max Height (m): %.2f vs %.2f" % (h_max_num, h_max_ex))

# Plot for Animation
plt.rcParams.update({'figure.max_open_warning': 0})
for i in range(len(y_arr)):
    plt.figure()
    plt.scatter(x_arr[i], y_arr[i], marker='o', c='b')
    plt.text(32, 14, '{:.2f} s'.format(t_arr[i]))
    plt.plot(x_arr, y_arr, c='b', label='Numerik')
    plt.plot(x_ex_arr, y_ex_arr, c='r', label='Analisis')
    plt.axhline(c='black')
    plt.axvline(c='black')
    plt.legend()
    plt.show()

谢谢

P.S。我以前从未使用过Python,所以这是我第一次使用它。

0 个答案:

没有答案